写入.txt 文件?
- 2024-10-23 08:47:00
- admin 原创
- 199
问题描述:
我怎样才能将一小段文本写入文件.txt
?我在 Google 上搜索了 3-4 个小时,但还是找不到如何操作。
fwrite();
有太多参数,我不知道如何使用它。
当您只想向.txt
文件中写入名称和几个数字时,最容易使用的函数是什么?
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf("
New contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c
[ %d ]
", name, number);
fclose(f);
解决方案 1:
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!
");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s
", text);
/* print integers and floats */
int i = 1;
float pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f
", i, pi);
/* printing single characters */
char c = 'A';
fprintf(f, "A character: %c
", c);
fclose(f);
解决方案 2:
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
");
fprintf(fp, "The string has %d words and keyword %s
", x, str);
fclose(fp);
解决方案 3:
嗯,你首先需要找一本关于 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);
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD