161

如何将一小段文本写入.txt文件?我已经在谷歌上搜索了 3-4 多个小时,但不知道该怎么做。

fwrite();有这么多参数,我不知道如何使用它。

当您只想将名称和几个数字写入.txt文件时,最容易使用的功能是什么?

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);
4

3 回答 3

295
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 pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);
于 2012-07-20T06:36:46.147 回答
23
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);
于 2012-07-20T06:50:02.150 回答
-4

好吧,您首先需要获得一本关于 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);
于 2012-07-20T06:37:19.140 回答