其他分享
首页 > 其他分享> > 文件操作

文件操作

作者:互联网

FILE

1. FILE * fopen( const char *filename, const char *mode );打开文件

打开当前路径下的文件,并指定打开方式.

| File access mode string | Meaning | Explanation | Action if file already exists | Action if file does not exist |
| ----------- | ----------- | ----------- | ----------- | ----------- | ----------- |
|"r"| read | Open a file for reading | read from start | failure to open |
|"w"| write| Create a file for writing| destroy contents| create new|
|"a"| append| Append to a file| write to end| create new|
|"r+"| read extended| Open a file for read/write| read from start| error|
|"w+"| write extended| Create a file for read/write|destroy contents|create new|
|"a+"| append extended| Open a file for read/write| write to end| create new|

1.1 代码示例

int main(){
	//D:\files\documents\test.txt
	//1.相对路径
	fopen("test.txt","r");//只读
	//2.绝对路径
	fopen("D:\\files\\documents\\test.txt","r");
	FILE* pf = fopen("test.txt","r");
	//3.判断打开是否成功
	if(pf == NULL)
		return 0;
	//4.关闭
	fclose(pf);
	pf = NULL;
	return 0;
}

当使用绝对路径打开时,注意要将反斜杠\转义

2. fclose(FILE* stream) 关闭文件流


功能 函数名 适用于
字符输入函数 fputc 所有输入流
字符输出函数 fgetc 所有输出流
字符串输入函数 fputs 所有输入流
字符串输出函数 fgets 所有输出流
格式化输入函数 fscanf 所有输入流
格式化输出函数 fprintf 所有输出流
二进制输入 fread 所有输入流
二进制输出 fwrite 所有输出流
//拓展
//stdin 键盘标准输入设备
//stdout屏幕标准输出设备
int main(){
    char c = fgetc(stdin);
    fputc(c,stdout);
    return 0;
}

3. fputc(char character,FILE* stream) 字符输入

向文件流中写入字符.

3.1 代码示例

//1.先创建一个文件流
FILE* pf = fopen("test.txt","w");
//2.判断该文件流是否创建成功,未创建则打印错误信息并结束
if(pf == NULL){
	printf("%s\n",strerror(errno));//include<string.h> include<error.h>
	return 0;
}
//3.逐个写入字符
fputc('h',pf);
fputc('e',pf);
fputc('l',pf);
fputc('l',pf);
fputc('o',pf);
//4.关闭文件流
fclose(pf);
//5.文件流赋空
pf = NULL;

3.1 进阶代码示例


//3.逐个写入字符
    char arr[11] = "hello world";
    int size = sizeof(arr)/sizeof(arr[0]);
    for(int i = 0;i<size;i++)
    fputc(arr[i],pf); 
//4.关闭文件流
fclose(pf);
//5.文件流赋空
pf = NULL;

4. fgetc( char character,FILE* stream) 字符输出

4.1 代码示例

EOF : end of file,文件的结尾

//1.先创建一个文件流
FILE* pf = fopen("test.txt","r");
//2.判断该文件流是否创建成功,未创建则打印错误信息并结束
if(pf == NULL){
	printf("%s\n",strerror(errno));//include<string.h> include<error.h>
	return 0;
}
//3.逐个输出字符
int c;
while((c = fgetc(pf)) != EOF){
    putchar(c);
}
//4.关闭文件流
fclose(pf);
//5.文件流赋空
pf = NULL;

5. char* fgets(char* _Buf, int _MaxCount, _iobuf * _File)获取文件流中一行文本

5.1 代码示例

    //1.新建输出缓冲区
    char outBuf[1024];
    //2.获取文件流
    FILE* pf = fopen("test.txt","r");
    //3.判断是否为空
    if(pf == NULL){
	      printf("%s\n",strerror(errno));//include<string.h> include<error.h>
	      return 0;
     }
    //3.fgets( )获取内容
    fgets(outBuf,1024,pf);
    printf("%s",outBuf);
    fgets(outBuf,1024,pf);
    printf("%s",outBuf);
    //4.关闭文件流
    fclose(pf);
    //5.赋空
    pf = NULL;
//hello world
//hello universe

该函数会将一行文本后的\n一同拷贝到字符缓冲区,所以打印时可以不用换行。

6. fputs(const char* str ,FILE* stream )

6.1 代码示例

    //1.新建输出缓冲区
    char inBuf[1024] = "hello nothing\n";
    //2.获取文件流
    FILE* pf = fopen("test.txt","w");
    //3.fgets( )获取内容
    fputs(inBuf,pf);
    //4.关闭文件流
    fclose(pf);
    //5.赋空
    pf = NULL;

fputs 函数若想换行,需要在第一个参数后加换行符。

7. fprintf(FILE* stream,const char *__format...)

7.1 代码示例

struct S{
    int a;
    double b;
    char c[];
};
int main(){
    //1.结构体申请动态空间
    struct S* s = (struct S*)malloc(sizeof(struct S));
    //2.判断是否申请成功
    if(s == NULL)
        return 0;
    //3.为柔性数组申请追加动态空间
    struct S* sp = realloc(s,20);
    //4.判断是否为空再赋给结构体指针
    if(sp == NULL)
        return 0;
    s = sp;
    //5.赋值
    s->a = 1314;
    s->b = 520.01;
    strcpy(s->c,"hello");//注意destination的空间大小足够
    //6.打开文件流
    FILE* pf = fopen("test.txt","w");
    //7.从文件流中格式化输出结构体到文件中
    fprintf(pf,"%d %lf %s",s->a,s->b,s->c);
    //8.关流赋空
    fclose(pf);
    fclose(s);
    fclose(sp);
    s = NULL;
    sp = NULL;
    pf = NULL;
}

8. fscanf()

8.1 代码示例

struct S{
    int a;
    double b;
    char c[];
};
    //1.结构体申请动态空间
    struct S* s = (struct S*)malloc(sizeof(struct S));
    //2.判断是否申请成功
    if(s == NULL)
        return 0;
    //3.为柔性数组申请追加动态空间
    struct S* sp = realloc(s,20);
    //4.判断是否为空再赋给结构体指针
    if(sp == NULL)
        return 0;
    s = sp;
    //5.打开文件流
    FILE* pf = fopen("test.txt","r");
    //6.
    fscanf(pf,"%d %lf %s",&(s->a),&(s->b),s->c);
    printf("%d %lf %s",s->a,s->b,s->c);
    //7.关流赋空
    fclose(pf);
    fclose(s);
    fclose(sp);
    s = NULL;
    sp = NULL;
    pf = NULL;

9. size_t fread( void *buffer, size_t size, size_t count,FILE *stream ) 二进制读文件

9.1 代码示例

//1.打开文件流
FILE* pf = fopen("test.txt","rb");//以二进制形式读
//2.判断文件流是否创建成功
if(pf == NULL)
	return 0;
//3.创建字符缓冲区存放读到的数据
char arr[1024] = {0};
//4.二进制读文件
fread(&arr,sizeof(arr)/sizeof(arr[0]),1,pf);
//5.打印
    for (int i = 0; i < 1024; i++) {
    printf("%c", arr[i]);
}
//6.关流
    fclose(pf);
    pf = NULL;

10. size_t fwrite( const void *buffer, size_t size, size_t count,FILE *stream ) 二进制形式写文件

10.1 代码示例

double a[5] = {1, 2, 3, 4, 5};
    FILE *pf = fopen("test.txt", "wb");
    assert(f1);//include <assert.h>
    fwrite(a, sizeof a[0], 5, f1);
    fclose(pf);
    pf = NULL;

11. void rewind( FILE *stream ) 重置文件指针

11.1 代码示例

FILE *f;
    char ch;
    char str[20];
 
    f = fopen("file.txt", "w");
    for (ch = '0'; ch <= '9'; ch++) {
        fputc(ch, f);
    }
    fclose(f);
 
    f = fopen("file.txt", "r");
    fread(str, 1, 10, f);
    puts(str);
 
    rewind(f);
    fread(str, 1, 10, f);
    puts(str);
    fclose(f);

//0123456789
//0123456789
 

12. int feof( FILE *stream ) 判断文件流是否结束

12.1 代码示例

 FILE* fp = fopen("test.txt", "r");
    if(!fp) {
        perror("File opening failed");
        return EXIT_FAILURE;
    }
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
       putchar(c);
    }
 
    if (ferror(fp))
        puts("I/O error when reading");
    else if (feof(fp))
        puts("End of file reached successfully");
 
    fclose(fp);

标签:文件,file,fclose,char,pf,FILE,操作,NULL
来源: https://www.cnblogs.com/DC-Flash/p/16383716.html