函数使用示例
读取
#include <stdio.h>
//成功返回流指针,失败返回空指针
int main(void)
{
FILE *file;
char filename[] = "./files/demo.txt";
char mode[] = "r";
file = fopen(filename,mode);
if(file == NULL)
{
printf("无法打开文件\n");
return 1;
}
int ch;
while((ch = fgetc(file)) != EOF){
printf("%c",ch);
}
//执行完毕后关闭流
fclose(file);
return 0;
}
使用 fgets 函数按行读取文件内容:
//成功返回流指针,失败返回空指针
int main(void)
{
FILE *file;
char filename[] = "./files/demo.txt";
char mode[] = "r+";
file = fopen(filename,mode);
if(file == NULL)
{
printf("无法打开文件\n");
return 1;
}
//int ch;
// while((ch = fgetc(file)) != EOF){
// printf("%c",ch);
// }
char buffer[1024];
while(fgets(buffer,sizeof(buffer),file) != NULL)
{
printf("%s",buffer);
}
//执行完毕后关闭流
fclose(file);
return 0;
}
写入
#include <stdio.h>
int main(int argc,int*argv[])
{
FILE *file;
char filename[] = "./files/demo2.txt";
char mode[] = "w";
int ch;
file = fopen(filename,mode);
if(file == NULL)
{
printf("无法打开文件");
return 1;
}
while((ch = getchar()) != EOF)
{
fputc(ch,file);
}
fclose(file);
return 0;
}
#include <stdio.h>
int main(int argc,int* argv[])
{
FILE* file;
char filename[] = "./files/exxample.txt";
char mode[] = "w";
char str[100];
file = fopen(filename,mode);
if(file == NULL)
{
printf("无法打开文件.\n");
return 1;
}
printf("请输入要写入的文件的字符串:\n");
fgets(str,sizeof(str),stdin);
fputs(str,file);
fclose(file);
return 0;
}
```