如何用fprintf函数把字符数组输出到文件上?
我主要想实现字符串的读取,这个函数能完成么?
分享到:
2010-06-22 17:35 提问者采纳
哥哥帮你看看~~~
如何用fprintf函数把字符数组输出到文件上?
实现如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[] = “hello”;
FILE *fp = NULL;
fp = fopen(“test.txt”, “w”);
if (fp == NULL)
{
printf(“Cann’t open the file!”);
exit(1);
}
else
{
fprintf(fp, “%s”, str);//把字符数组str的内容输到文件fp中去
fclose(fp);
}
return 0;
}
我主要想实现字符串的读取,这个函数能完成么?
不是太明白你的意思, 读到哪去? 到文件中去的话就是上面哥哥写的代码!
要是反过来也就是把文件中的字符串读到变量中去的话就用fscanf函数,
如下:
#include <stdio.h>
#include <stdlib.h>
#define STR_LEN 1024
int main()
{
char str2[STR_LEN] = {0};
FILE *fp = NULL;
fp = fopen(“test.txt”, “r”);
if (fp == NULL)
{
printf(“Cann’t open the file!”);
exit(1);
}
else
{
fscanf(fp, “%s”, str2);//把文件fp中的内容以字符串的形式存到字符数组str2中
printf(“%s\n”, str2);
fclose(fp);
}
return 0;
}
不知道是否符合你的意思, 如果不符合请你把你需求表述清楚点~~~
提问者评价
谢谢您