fopen( 参数1,参数2)
//例
fopen("/Users/mac/Desktop/tmp/test.txt", "r")打开文件使用fopen()函数,函数可以接收两个参数,第一个参数表示文件位置,第二个参数表示打开之后可进行的操作
参数1:
参数1表示文件位置,不同的系统有不同的书写方式
Linus系统、mac系统:/temp/test,txt
windows系统:C:\\tmp\\test.txt
注:对于mac系统想要获取文件路径,可以这样操作:右击文件夹选择“显示简介”,然后选中位置一栏右击拷贝即可;
参数2:
直接调用fclose()函数:fclose(FILE *fp);
int fputs(int c,FILE *fp)函数:把参数 c 的字符值写入到 fp 所指向的输出流中
int fputs( const char s, FILE fp ):写入字符串
int fprintf(fp, const char *s):同样可以写入字符串
例子:
#include <stdio.h>
 
int main()
{
   FILE *fp = NULL;
 
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}
/* 文件中显示如下
This is testing for fprintf...
This is testing for fputs...
*/int fgetc( FILE * fp ): 读取单个字符
char fgets( char buf, int n, FILE *fp ):读取字符串,遇到‘\n‘时结束
fscanf(FILE ,chra *buf): 读取字符串,遇到空格时结束;
例子:
#include <stdio.h>
 
int main()
{
   FILE *fp = NULL;
   char buff[255];
 
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1: %s\n", buff );
 
   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
 
}
/* 运行结果
1: This
2: is testing for fprintf...
3: This is testing for fputs...
*/补充:一个文件可能会有好多行,想要读取整个文件,但是fscanf() fgets() 函数都不行,因此定义一个ch=fgetc(),利用循环判断读取的最后一个字符是不是文件结束EOF,如果不是就继续调用函数fgets()函数;代码如下;
#include<stdio.h>
char buff[255];
int main()
{
    FILE *fp = NULL;
    fp = fopen("/Users/mac/Desktop/tmp/test.txt", "r");
    char ch = '\0';
    while(ch!=EOF)
    {
        
        fgets(buff, 255, (FILE*)fp);
        printf("%s\n", buff);
        ch=fgetc(fp);
    }   
}
/* 运行结果
This is testing for fprintf...
his is testing for fputs...
Program ended with exit code: 0
*/原文:https://www.cnblogs.com/zhulmz/p/11710727.html