九、文件操作

 

一、什么是文件

1.1 程序文件

包括源程序文件(后缀为.c),目标文件(windows环境后缀为.obj),可执行程序(windows环境后缀为.exe)。

1.2 数据文件

文件的内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读取数据的文件,或者输出内容的文件。

1.3 文件名

一个文件要有一个唯一的文件标识,以便用户识别和引用。
文件名包含3部分:文件路径+文件名主干+文件后缀
例如: c:\code\test.txt
为了方便起见,文件标识常被称为文件名

1.4 文件类型

根据数据的组织形式,数据文件被称为文本文件或者二进制文件。

1.4.1 文本文件

数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件

1.4.2 二进制文件

如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件

1.4.3 文件存储方式

一个数据在内存中是怎么存储的呢?
字符一律以ASCII形式存储,数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。
如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而
二进制形式输出,则在磁盘上只占4个字节(VS2013测试)。

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>

int main()
{
    int a = 10000;
    FILE *pFile = fopen("test.txt", "wb");
    fwrite(&a, 4, 1, pFile);
    fclose(pFile);
    pFile = NULL;
    return 0;
}

 

 

1.5 文件缓冲区

ANSIC 标准采用 "缓冲文件系统" 处理的数据文件的,所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块 "文件缓冲区"。从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上。如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C编译系统决定的.

 

 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<windows.h>

int main()
{
    FILE *pFile = fopen("test02.txt", "wt");
    fputs("abcdef",  pFile);
    printf("睡眠10秒 - 已经写数据了,打开test.txt文件,发现文件没有内容\n");
    Sleep(10000);
    printf("刷新缓冲区\n");
    fflush(pFile);
    printf("再睡眠10秒-此时,再次打开test.txt文件,文件有内容了\n");
    Sleep(10000);
    fclose(pFile);
    //注:fclose在关闭文件的时候,也会刷新缓冲区
    pFile = NULL;
    return 0;
}

1.6 文件指针

缓冲文件系统中,关键的概念是“文件类型指针”,简称 "文件指针"。每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名字,文件状态及文件当前的位置等)。这些信息是保存在一个结构体变量中的。该结构体类型是有系统声明的,取名FILE.
例如,VS2013编译环境提供的stdio.h 头文件中有以下的文件类型申明:

struct _iobuf {
    char *_ptr;
    int _cnt;
    char *_base;
    int _flag;
    int _file;
    int _charbuf;
    int _bufsiz;
    char *_tmpfname;
};
typedef struct _iobuf FILE;

不同的C编译器的FILE类型包含的内容不完全相同,但是大同小异。每当打开一个文件的时候,系统会根据文件的情况自动创建一个FILE结构的变量,并填充其中的信息,使用者不必关心细节。一般都是通过一个FILE的指针来维护这个FILE结构的变量,这样使用起来更加方便。

下面我们可以创建一个FILE*的指针变量:

FILE* pf;//文件指针变量

定义pf是一个指向FILE类型数据的指针变量。可以使pf指向某个文件的文件信息区(是一个结构体变量)。通过该文件信息区中的信息就能够访问该文件。也就是说,通过文件指针变量能够找到与它关联的文件。

 

 

 

二、文件的打开与关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。
在编写程序的时候,在打开文件的同时,都会返回一个 FILE* 的指针变量指向该文件,也相当于建立了指
针和文件的关系。
ANSIC 规定使用fopen函数来打开文件,fclose来关闭文件。

//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream );
文件使用方式含义如果指定文件不存在
"r"(只读) 为了输入数据,打开一个已经存在的文本文件 出错
"w"(只写) 为了输出数据,打开一个文本文件 建立一个新的文件
"a"(追加) 向文本文件尾添加数据 建立一个新的文件
"rb"(只读) 为了输入数据,打开一个二进制文件 出错
"wb"(只写) 为了输出数据,打开一个二进制文件 建立一个新的文件
"ab"(追加) 向一个二进制文件尾添加数据 出错
"r+"(读写) 为了读和写,打开一个文本文件 出错
"w+"(读写) 为了读和写,建议一个新的文件 建立一个新的文件
"a+"(读写) 打开一个文件,在文件尾进行读写 建立一个新的文件
"rb+"(读写) 为了读和写打开一个二进制文件 出错
"wb+"(读写) 为了读和写,新建一个新的二进制文件 建立一个新的文件
"ab+"(读写) 打开一个二进制文件,在文件尾进行读和写 建立一个新的文件

 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<errno.h>
#include<string.h>

int main()
{
    FILE *pFile = fopen("test02.txt", "r");
    if (pFile == NULL)
    {
        printf("%s\n", strerror(errno));
        return 0;
    }
    // 打开成功
    // 关闭文件
    fclose(pFile);
    pFile = NULL;
    return 0;
}

三、文件的顺序读写

功能函数名适用于
字符输入函数 fgetc 所有输入流
字符输出函数 fputc 所有输出流
文本行输入函数 fgets 所有输入流
文本行输出函数 fputs 所有输出流
格式化输入函数 fscanf 所有输入流
格式化输出函数 fprintf 所有输出流
二进制函数 fread 文件
二进制输出 fwrite 文件

 

3.1 fputc、fgetc

3.1.1 fputc、fgetc 的基本使用

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

int main()
{
    FILE *pFilew = fopen("test02.txt", "w");
    if (pFilew == NULL)
    {
        printf("%s\n", strerror(errno));
        return 0;
    }
    // 写文件
    fputc('w', pFilew);
    fputc('a', pFilew);
    fputc('n', pFilew);
    fputc('g', pFilew);

    // 关闭文件
    fclose(pFilew);
    pFilew = NULL;
    FILE *pFiler = fopen("test02.txt", "r");
    printf("%c\n", fgetc(pFiler));  // w
    printf("%c\n", fgetc(pFiler));  // a
    printf("%c\n", fgetc(pFiler));  // n
    printf("%c\n", fgetc(pFiler));  // g
    return 0;
}

3.1.2 fputc、fgetc 标准输入输出流

/*
    键盘 ---- 标准输入设备  ---- stdin
    屏幕 ---- 标准输出设备  ---- stdout
    键盘和屏幕是默认打开的两流设备
    
    stdin FILE*
    stdout FILE*
    stderr FILE*
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    int ch = fgetc(stdin);
    fputc(ch, stdout);
    return 0;

}

3.2 fgets、fputs

3.2.1 fgets、fputs的基本使用

char *fgets(char *string, int n, FILE *stream);  //将会stream的内部一行最大读取n个字节读取到 string里面去
int fputs(const char *string, FILE *stream);     // 将一行string写入到 stream中
/*
char *fgets(char *string, int n, FILE *stream);  //将会stream的内部一行最大读取n个字节读取到 string里面去
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    char buf[1024] = { 0 };
    FILE *pFile = fopen("test02.txt", "r");   // wang\n yong
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    //读文件
    fgets(buf, 10244, pFile);
    printf("%s", buf);   // wang
    fgets(buf, 10244, pFile);
    printf("%s", buf);   // yong
    fclose(pFile);
    pFile = NULL;
    return 0;
}

/*
int fputs(const char *string, FILE *stream);     // 将一行string写入到 stream中
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    char buf[1024] = { 0 };
    FILE *pFile = fopen("test02.txt", "w");   // wang\n yong
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    //写文件
    fputs("Hello\n", pFile);
    fputs("World", pFile);

    fclose(pFile);
    pFile = NULL;
    return 0;
}

3.2.2 fputs、fgets 标准输入输出流

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

int main()
{
    // 从键盘上读取一行文本信息
    char buf[1034] = { 0 };
    fgets(buf, 1024, stdin);
    fputs(buf, stderr);

    return 0;
}

3.3 fprintf、fscanf

3.3.1 fprintf、fscanf 的基本使用

int fprint(FILE *stream, const char *format[, argument]...);
int fscanf(FILE *stream, const char *format[,argument]...);
/*
int fprint(FILE *stream, const char *format[, argument]...)
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S
{
    int n;
    float score;
    char arr[10];
};

int main()
{
    struct S s = { 100, 3.14f, "wangyong" };
    FILE *pf = fopen("test02.txt", "w");
    if (pf == NULL)
    {
        printf("%s\n", strerror(errno));
        return 0;
    }
    // 格式化形式写文件
    fprintf(pf, "%d, %f, %s", s.n, s.score, s.arr);
    fclose(pf);

    return 0;
}

 

 

/*
int fscanf(FILE *stream, const char *format[,argument]...);
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S
{
    int n;
    float score;
    char arr[10];
};

int main()
{
    struct S s = {0};
    FILE *pf = fopen("test02.txt", "r");
    if (pf == NULL)
    {
        printf("%s\n", strerror(errno));
        return 0;
    }
    // 格式化形式输入数据
    
    fscanf(pf, "%d, %f, %s", &(s.n), &(s.score), s.arr);
    printf("%d, %f, %s\n", s.n, s.score, s.arr);
    fclose(pf);

    return 0;
}

3.3.2 fprintf、fscanf 标准输入输出流

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S 
{
    int n; 
    float score;
    char arr[10];
};

int main()
{
    struct S s = { 0 };
    fscanf(stdin, "%d,%f,%s", &(s.n), &(s.score), s.arr);
    fprintf(stdout, "%d, %f, %s", s.n, s.score, s.arr);
    return 0;
}

3.4 对比函数(scanf/fscanf/sscanf,printf/fprintf/sprintf)

scanf/printf 是针对标准输入输出流的格式化输入输出语句;
fscanf/fprintf 是针对所有输入输出流的格式化输入输出语句;
sscanf/sprintf  sscanf是从字符串中读取格式化的数据, sprintf是把格式化数据输出成(存储到)字符串
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S
{
    int n;
    float score;
    char arr[10];
};

int main()
{

    struct S s = {10, 3.14, "abcdef"};
    struct S tmp = { 0 };
    char buf[1024] = { 0 };
    // 将格式化的数据转换成字符串存储到buf
    sprintf(buf, "%d %f %s", s.n, s.score, s.arr);
    printf("%s\n", buf);
    // 从buf中读取格式化的数据到tmp中
    sscanf(buf, "%d %f %s",&(tmp.n), &(tmp.score), tmp.arr);
    printf("%d %f %s", tmp.n, tmp.score, tmp.arr);
    return 0;
}

3.5 fread、fwrite

3.5.1 fread、fwrite的基本使用

size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
size_s fread(const void *buffer, size_t size, size_t count, FILE *stream);
/*
size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S
{
    char name[20];
    int age;
    double score;
};

int main()
{
    struct S s = { "wangyong", 27, 100 };
    FILE *pFile = fopen("test.txt", "wb");
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    fwrite(&s, sizeof(struct S), 1, pFile);
    fclose(pFile);
    pFile = NULL;

    return 0;
}

 

 

/*
size_s fread(const void *buffer, size_t size, size_t count, FILE *stream);
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

struct S
{
    char name[20];
    int age;
    double score;
};

int main()
{
    struct S tmp = {0};
    FILE *pFile = fopen("test.txt", "rb");
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    fread(&tmp, sizeof(struct S), 1, pFile);
    printf("%s %d %lf", tmp.name, tmp.age, tmp.score);
    fclose(pFile);
    pFile = NULL;

    return 0;
}

四、文件的随机读写

4.1 fseek函数

int fseek(FILE *stream, long offset, int origin);   
// offset:偏移量, origin:当前位置  (SEEK_SET, SEEK_CUR, SEEK_END)
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>

int main()
{
    FILE *pFile = fopen("test02.txt", "r");  // abcdef
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    // 1. 定位文件指针
    fseek(pFile, 4, SEEK_CUR);
    // 2. 读取文件
    char ch = fgetc(pFile);
    printf("%c\n", ch);  // e

    fseek(pFile, -2, SEEK_END);
    ch = fgetc(pFile);
    printf("%c\n", ch);  // e

    fclose(pFile);
    pFile = NULL;

    return 0;
}

4.2 ftell函数(返回文件指针相对于起始位置的偏移量)

long int ftell ( FILE * stream );
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    FILE *pFile = fopen("test02.txt", "r");  // abcdef
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }


    fseek(pFile, -2, SEEK_END);
    int pos = ftell(pFile);   // ftell 当前指针相对于文件起始位置的偏移量
    printf("%d", pos);   // 4

    fclose(pFile);
    pFile = NULL;

    return 0;
}

4.3 rewind函数(让文件指针的位置回到文件的起始位置)

void rewind ( FILE * stream );
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    FILE *pFile = fopen("test02.txt", "r");  // abcdef
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }

    fseek(pFile, -2, SEEK_END);
    int pos = ftell(pFile);   // ftell 当前指针相对于文件起始位置的偏移量
    printf("%d\n", pos);   // 4
    rewind(pFile);  // 将文件指针返回到文件最开始位置
    char ch = fgetc(pFile);
    printf("ch = %c\n", ch);  // ch = a
    fclose(pFile);
    pFile = NULL;

    return 0;
}

 

 

五、文件结束的判定

5.1 EOF的使用

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    FILE *pFile = fopen("test.txt", "r"); // 文件为空
    if (pFile == NULL)
    {
        printf("%s", strerror(errno));
        return 0;
    }
    int ch = fgetc(pFile);
    if (ch == EOF)
    {
        printf("ch = %d\n", ch);  // ch = -1
    }
    
    return 0;
}

5.2 strerror和perror的区别

strerror 把错误码对应的错误信息的字符串地址返回, 头文件 string.h 具体使用见上面
perror("haha") ---> haha: No such file or directory。 perror在报错的时候,会奖项perror后面的输出内容输出来,然后加上 : , 再加上错误的具体信息。不需要引用头文件。

5.3 被错误使用的feof

牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束。
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束。

1. 文本文件读取是否结束,判断返回值是否为EOF ( fgetc ),或者NULL ( fgets )
例如:
  fgetc 判断是否为EOF .
  fgets 判断返回值是否为NULL .
2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
例如:
  fread判断返回值是否小于实际要读的个数。

5.3.1 读文本文件

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<errno.h>


int main()
{
    FILE *pFile = fopen("test.txt", "r");
    if (pFile == NULL)
    {
        perror("open file test.txt");
        return 0;
    }
    int ch = 0;
    while ((ch = fgetc(pFile)) != EOF)
    {
        putchar(ch);
    }
    if (ferror(pFile))
    {
        printf("error\n");
    }
    else if (feof(pFile))
    {
        printf("end of file\n");
    }
    fclose(pFile);
    pFile = NULL;

    return 0;
}

5.3.2 读二进制文件

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

enum 
{ 
    SIZE = 5 
};

int main(void)
{
    double a[SIZE] = { 1., 2., 3., 4., 5. };
    FILE *fp = fopen("test.bin", "wb"); // 必须用二进制模式
    fwrite(a, sizeof *a, SIZE, fp); // 写 double 的数组
    fclose(fp);

    double b[SIZE];
    fp = fopen("test.bin", "rb");
    size_t ret_code = fread(b, sizeof *b, SIZE, fp); // 读 double 的数组
    if (ret_code == SIZE) 
    {
        puts("Array read successfully, contents: ");
        for (int n = 0; n < SIZE; ++n)
        {
            printf("%f ", b[n]);
        }
            
        putchar('\n');
    }
    else 
    { // error handling
        if (feof(fp))
        {
            printf("Error reading test.bin: unexpected end of file\n");
        }
            
        else if (ferror(fp)) 
        {
            perror("Error reading test.bin");
        }
    }

    fclose(fp);
}

 

posted on 2020-11-18 08:38  软饭攻城狮  阅读(80)  评论(0编辑  收藏  举报

导航