Linux 写入 .txt 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11573974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write to .txt file?
提问by Stian Olsen
How can I write a little piece of text into a .txt
file?
I've been Googling for over 3-4 hours, but can't find out how to do it.
如何将一小段文本写入.txt
文件?我已经在谷歌上搜索了 3-4 个小时,但不知道怎么做。
fwrite();
has so many arguments, and I don't know how to use it.
fwrite();
有这么多参数,我不知道如何使用它。
What's the easiest function to use when you only want to write a name and a few numbers to a .txt
file?
当您只想将名称和几个数字写入.txt
文件时,最容易使用的函数是什么?
Edit: Added a piece of my code.
编辑:添加了我的一段代码。
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf("\nNew contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c\n[ %d ]\n\n", name, number);
fclose(f);
采纳答案by Stian Olsen
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
回答by Jeeva
Well, you need to first get a good book on C and understand the language.
好吧,您首先需要获得一本关于 C 的好书并了解该语言。
FILE *fp;
fp = fopen("c:\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
回答by cppcoder
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);