天天看点

C语言从入门到精通——文件操作

共用体和联合体:

union test {

  char ch;

  short sh;

  int var;
};

联合体,内部所有成员变量地址一致。等同于整个联合体的地址。

  联合体的大小,是内部成员变量中,最大的那个成员变量的大小。(对齐)

  修改其中任意一个成员变量的值,其他成员变量会随之修改。      

枚 举:

enum  color { 枚举常量 };

enum  color { red, green, blue, black, pink, yellow };

   枚举常量: 是整型常量。不能是浮点数。可以是负值。 默认初值从 0 开始,后续常量较前一个常量 +1.

       可以给任意一个常量赋任意初值。后续常量较前一个常量 +1      

读写文件与printf、scanf关联

printf -- 屏幕 -- 标准输出

scanf -- 键盘 -- 标准输入

perror -- 屏幕 -- 标准错误      

系统文件:

标准输入 -- stdin -- 0

标准输出 -- stdout -- 1

标准错误 -- stderr -- 2

应用程序启动时,自动被打开,程序执行结束时,自动被关闭。 ---- 隐式回收。

1s = 1000ms 

1ms = 1000us

1us == 1000ns      

文件指针和普通指针区别:

FILE *fp = NULL;

借助文件操作函数来改变 fp 为空、野指针的状况。 fopen();  --> 相当于 fp = malloc();

操作文件, 使用文件读写函数来完成。 fputc、fgetc、fputs、fgets、fread、fwrite      

文件分类:

设备文件:

  屏幕、键盘、磁盘、网卡、声卡、显卡、扬声器...

磁盘文件:

  文本文件:   ASCII

  二进制文件:  0101 二进制编码      

文件操作一般步骤:

1. 打开文件 fopen()  --》 FILE *fp;

2. 读写文件 fputc、fgetc、fputs、fgets、fread、fwrite

3. 关闭文件 fclose()      

打开、关闭文件函数:

FILE * fopen(const char * filename, const char * mode);

  参1:待打开文件的文件名(访问路径)

  参2:文件打开权限:

    "r": 只读方式打开文件, 文件不存在,报错。存在,以只读方式打开。

    "w": 只写方式打开文件, 文件不存在,创建一个空文件。文件如果存在,清空并打开。

    "w+":读、写方式打开文件,文件不存在,创建一个空文件。文件如果存在,清空并打开。

    "r+":读、写方式打开文件, 文件不存在,报错。存在,以读写方式打开。

    "a": 以追加的方式打开文件。

    "b": 操作的文件是一个二进制文件(Windows)

  返回值:成功:返回打开文件的文件指针

    失败:NULL


int fclose(FILE * stream);

  参1:打开文件的fp(fopen的返回值)

  返回值:成功 :0, 失败: -1;      

文件访问路径:

绝对路径:

  从系统磁盘的 根盘符开始,找到待访问的文件路径

  Windows书写方法:

    1)C:\\Users\\afei\\Desktop\\06-文件分类.avi

    2)C:/Users/afei/Desktop/06-文件分类.avi  --- 也使用于Linux。

相对路径:

  1)如果在VS环境下,编译执行(Ctrl+F5),文件相对路径是指相对于 day10.vcxproj 所在目录位置。

  2)如果是双击 xxx.exe 文件执行,文件的相对路径是相对于 xxx.exe 所在目录位置。      

按字符写文件 fputc:

int fputc(int ch, FILE * stream);

  参1:待写入的 字符

  参2:打开文件的fp(fopen的返回值)

  返回值: 成功: 写入文件中的字符对应的ASCII码

     失败: -1


练习:写26个英文字符到文件中。      

按字符读文件 fgetc

int fgetc(FILE * stream);

  参1:待读取的文件fp(fopen的返回值)

  返回值: 成功:读到的字符对应的ASCII码

     失败: -1

文本文件的结束标记: EOF ---》 -1      

feof()函数:

int feof(FILE * stream);

  参1: fopen的返回值

  返回值: 到达文件结尾-->非0【真】
      
     没到达文件结尾-->0【假】

作用: 
  用来判断到达文件结尾。 既可以判断文本文件。也可以判断 二进制文件。

特性:

  要想使用feof()检测文件结束标记,必须在该函数调用之前,使用读文件函数。

  feof()调用之前,必须有读文件函数调用。      

fgets()函数:

获取一个字符串, 以\n作为结束标记。自动添加 \0. 空间足够大 读\n, 空间不足舍弃\n, 必须有\0。

char * fgets(char * str, int size, FILE * stream);

  char buf[10];   hello --> hello\n\0

  返回值: 成功: 读到的字符串

     失败: NULL      

fputs()函数:

写出一个字符串,如果字符串中没有\n, 不会写\n。

int fputs(const char * str, FILE * stream);

  返回值: 成功: 0

     失败: -1      

练习: 获取用户键盘输入,写入文件。

假定:用户写入“:wq”终止接收用户输入,将之前的数据保存成一个文件。      
#include <iostream>
#include <cstring>

using namespace std;
int main() {
    FILE *fp = fopen("test.txt","w");
    char buff[4096] = {0};
    if(fp==NULL){
        perror("fopen error!");
        return -1;
    }
    while (1){
        fgets(buff,4096,fp);
        if(strcmp(buff,":wq\n")==0){
            break;
        }
        fputs(buff,fp);
    }
    fclose(fp);
}      

练习: 文件版四则运算:

1. 封装 write_file 函数,将4则运算表达式写入。

  FILE * fp = fopen("w");

  fputs("10/4=\n", fp);

  fputs("10+4=\n", fp);
  ....

  fputs("10*4=\n", fp);

2. 封装 read_file 函数, 将4则运算表达式读出,拆分,运算,写回。

  1) 读出:

    FILE * fp = fopen("r");

    while (1) {

      fgets(buf, sizeof(buf), fp);  // buf中存储的 4则运算表达式
    }

  2) 拆分:

    sscanf(buf, "%d%c%c=\n", &a, &ch, &b);  // 得到运算数, 运算符

  3) 根据运算符,得到运算结果

    switch(ch) {

      case '+':
        a+b;
    }

  4) 拼接 结果到  运算式 上

    char result[1024];

    sprintf(reuslt, "%d%c%d=%d\n", a, ch, b, a+b);    // reuslt 中包含带有结果的 运算式。

  5)将 多个带有结果的运算 拼接成一个字符串。

    char sum_ses[4096]; // 存总的字符串  -- "10/2=5\n10*3=30\n4+3=7\n8-6=2\n"

    strcat(sum_ses,reuslt);  // 在while中循环拼接

  6) 重新打开文件, 清空原有 4则运算表达式

    fclose(fp);

    fp = fopen("w");

  7) 将 拼接成一个字符串。写入到空的文件中

    fputs(sum_res);      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

typedef union test{
    char ch;
    short sh;
    int a;
}test_t;

int main(){
    test_t obj;
    obj.a = 0x87654321;
    printf("&obj    = %p\n", &obj);
    printf("&obj.ch = %p\n", &obj.ch);
    printf("&obj.sh = %p\n", &obj.sh);
    printf("&obj.a  = %p\n", &obj.a);

    printf("sizeof(test_t) = %u\n", sizeof(test_t));

    printf("a  = 0x%x\n", obj.a);
    printf("sh = 0x%x\n", obj.sh);
    printf("ch = 0x%x\n", obj.ch);

    obj.ch = 0xFF;

    printf("a  = 0x%x\n", obj.a);
    printf("sh = 0x%x\n", obj.sh);
    printf("ch = 0x%x\n", obj.ch);

    system("pause");
    return EXIT_SUCCESS;
    return 0;
}

//      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
//-6 -4
enum  color { red, green = -5, blue,
        black, //17
        pink = 18,
        yellow };//19


int main(void)
{
    int flg = 2;

    // ......

    if (flg == blue)
    {
        printf("blue is 2\n");
    }
    else
    {
        printf("blue is not 2, blue = %d\n", blue);
    }
    printf("yellow = %d\n", yellow);
    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    //fclose(stdout);

    printf("hello file\n");

    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    FILE *fp = NULL;

    fp = fopen("test2.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");  //printf("fopen error\n");  :xxxxxxx
        getchar();
        return -1;
    }

    fclose(fp);
    printf("------------finish\n");

    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    char *filename = "test04.txt";

    FILE *fp = fopen(filename, "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return -1;
    }

    int ret = fputc('A', fp);
    printf("ret = %d\n", ret);
    fclose(fp);
    printf("---------------finish\n");
    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    char *filename = "test04.txt";
    int ret = 0;

    FILE *fp = fopen(filename, "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return -1;
    }
    char ch = 'a';

    while (ch <= 'z')
    {
        ret = fputc(ch, fp);
        if (ret == -1)
        {
            perror("fputc eror");
            return -1;
        }
        ch++;
    }

    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>


int main(void)
{
    char *buf = "abcdefghijklmnopqrstuvwxyz";

    char *filename = "test04.txt";
    int ret = 0;

    FILE *fp = fopen(filename, "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return -1;
    }
    int n = strlen(buf);
    for (size_t i = 0; i < n; i++)
    {
        ret = fputc(buf[i], fp);
        if (ret == -1)
        {
            perror("fputc eror");
            return -1;
        }
    }
    fclose(fp);

    system("pause");
    return EXIT_SUCCESS;
}      

读取文件

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void write_file()
{
    FILE *fp = fopen("05test.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return ;
    }

    fputc('a', fp);
    fputc('b', fp);
    fputc('c', fp);
    fputc('d', fp);

    fclose(fp);
}
void read_file()
{
    char ch = 0;

    FILE *fp = fopen("05test.txt", "r");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }

    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
        {
            break;
        }
        printf("%d\n", ch);
    }

    fclose(fp);
}

int main(void)
{
    write_file();
    read_file();
    system("pause");
    return EXIT_SUCCESS;
}      

10/2= fgets(buf, 4096, 文件fp) —>“10/2=\n” --> 10 / 2 sscanf(buf, “%d%c%d=\n”, &a, &c, &b); -> a=10, b=2, c=‘/’

10*3=

4+3=

8-6=

switch © {

case '/':

      a / b;
      break;

    case '+':
      a + b;

      break;

    ....
  }

  fopen("", "w");

  char result[];   sprintf()/strcat()  --> "10/2=5\n10*3=30\n4+3=7\n8-6=2\n"  --> fputs(result, fp)      

=====>

10/2=5

10*3=30

4+3=7

8-6=2

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void write_file08()
{
    FILE *fp = fopen("test08.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }

    fputs("10/2=\n", fp);
    fputs("10*3=\n", fp);
    fputs("4-2=\n", fp);
    fputs("10+2=\n", fp);

    fclose(fp);
}

int calc(char ch, int a, int b)
{
    switch (ch)
    {
        case '/':
            return a / b;

        case '+':
            return a + b;

        case '-':
            return a - b;

        case '*':
            return a *b;
        default:
            break;
    }
}

void read_file08()
{
    char buf[4096] = {0};
    char result[4096] = {0};

    char sum_res[4096] = {0};

    int a, b, ret;
    char ch;

    FILE *fp = fopen("test08.txt", "r");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }

    while (1)
    {
        fgets(buf, 4096, fp);  //buf = "10/2=\n\0";
        if (feof(fp))
        {
            break;
        }
        sscanf(buf, "%d%c%d=\n", &a, &ch, &b);

        sprintf(result, "%d%c%d=%d\n", a, ch, b, calc(ch, a, b));  // 10 / 2 = 5;

        strcat(sum_res, result);
    }
    fclose(fp);

    fp = fopen("test08.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }
    fputs(sum_res, fp);
    fclose(fp);
}


int main(void)
{
    write_file08();
    getchar();
    read_file08();

    system("pause");
    return EXIT_SUCCESS;
}      

printf — sprintf — fprintf:

变参函数:参数形参中 有“...”, 最后一个固参通常是格式描述串(包含格式匹配符), 函数的参数个数、类型、顺序由这个固参决定。

printf("hello");
  
printf("%s", "hello");

printf("ret = %d+%d\n", 10, 5);

printf("%d = %d%c%d\n", 10+5, 10, '+', 5);      --> 屏幕


char buf[1024];   //缓冲区  

sprintf(buf, "%d = %d%c%d\n", 10+5, 10, '+', 5);    --> buf 中

FILE * fp = fopen();

fprintf(fp, "%d = %d%c%d\n", 10+5, 10, '+', 5);     --> fp 对应的文件中      

scanf — sscanf — fscanf

scanf("%d", &m);    键盘 --> m


char str[] = "98";

sscanf(str, "%d", &m);    str --> m


FILE * fp = fopen("r");

fscanf(fp, "%d", &m);   fp指向的文件中 --> m      

fprintf()函数:

写

int fprintf(FILE * stream, const char * format, ...);      

fscanf()函数:

读

int fscanf(FILE * stream, const char * format, ...);

  成功:正确匹配的个数。

  失败: -1

1) 边界溢出。 存储读取的数据空间。在使用之前清空。

2)fscanf函数,每次在调用时都会判断下一次调用是否匹配参数2, 如果不匹配提前结束读文件。(feof(fp) 为真)。      

练习:文件版排序

生成随机数,写入文件。将文件内乱序随机数读出,排好序再写回文件。      

fgetc — fputc

fgets — fputs

fprintf – fscanf 默认处理文本文件。

fwrite()函数: 既可处理以文本文件。也处理二进制文件。

写出数据到文件中。

stu_t stu[4] = { ...... };

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

  参1:待写出的数据的地址

  参2:待写出数据的大小

  参3:写出的个数        -- 参2 x 参3 = 写出数据的总大小。

  参4:文件

  返回值: 成功:永远是 参3 的值。 --- 通常将参2 传 1. 将参3传实际写出字节数。

     失败:0      

fread()函数:

从文件fp中读出数据。

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

  参1:读取到的数据存储的位置

  参2:一次读取的字节数

  参3:读取的次数        -- 参2 x 参3 = 读出数据的总大小

  参4:文件

  返回值: 成功:参数3.  --- 通常将参2 传 1. 将参3传欲读出的字节数。       

     0:读失败 -- 到达文件结尾 -- feof(fp)为真。      

练习:大文件拷贝

已知一个任意类型的文件,对该文件复制,产生一个相同的新文件。

1. 打开两个文件, 一个“r”, 另一“w”

2. 从r中 fread , fwrite到 w 文件中。

3. 判断到达文件结尾 终止。  

4. 关闭。

注意: 在windows下,打开二进制文件(mp3、mp4、avi、jpg...)时需要使用“b”。如:“rb”、“wb”      

随机位置 读:

文件读写指针。在一个文件内只有一个。

fseek():

  int fseek(FILE *stream, long offset, int whence);

    参1:文件

    参2:偏移量(矢量: + 向后, - 向前)

    参3: SEEK_SET:文件开头位置

      SEEK_CUR:当前位置

      SEEK_END:文件结尾位置

  返回值: 成功:0, 失败: -1

ftell():

  获取文件读写指针位置。

  long ftell(FILE *stream);

  返回:从文件当前读写位置到起始位置的偏移量。

  
  借助 ftell(fp) + fseek(fp, 0, SEEK_END); 来获取文件大小。

rewind():

  回卷文件读写指针。 将读写指针移动到起始位置。

  void rewind(FILE *stream);      

Linux和windows文件区别:

1)对于二进制文件操作, Windows 使用“b”, Linux下二进制和文本没区别。

2)windows下,回车 \r, 换行 \n。 \r\n  , Linux下 回车换行\n

3) 对文件指针,先写后读。windows和Linux效果一致。

         先读后写。Linux无需修改。windows下需要在写操作之前添加 fseek(fp, 0, SEEK_CUR); 来获取文件读写指针,使之生效。      

获取文件状态:

打开文件,对于系统而言,系统资源消耗较大。

int stat(const char *path, struct stat *buf);

  参1: 访问文件的路径

  参2: 文件属性结构体

  返回值: 成功: 0, 失败: -1;      
int remove(const char *pathname); 删除文件。

int rename(const char *oldpath, const char *newpath);  重名文件      
标准输出-- stdout -- 标准输出缓冲区。   写给屏幕的数据,都是先存缓冲区中,由缓冲区一次性刷新到物理设备(屏幕)

标准输入 -- stdin -- 标准输入缓冲区。 从键盘读取的数据,直接读到 缓冲区中, 由缓冲区给程序提供数据。

预读入、缓输出。

行缓冲:printf(); 遇到\n就会将缓冲区中的数据刷新到物理设备上。

全缓冲:文件。 缓冲区存满, 数据刷新到物理设备上。

无缓冲:perror。 缓冲区中只要有数据,就立即刷新到物理设备。



文件关闭时, 缓冲区会被自动刷新。  隐式回收:关闭文件、刷新缓冲区、释放malloc

手动刷新缓冲区: 实时刷新。

  int fflush(FILE *stream);

    成功:0

    失败:-1      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void write_file08()
{
    FILE *fp = fopen("test08.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }

    fputs("10/2=\n", fp);
    fputs("10*3=\n", fp);
    fputs("4-2=\n", fp);
    fputs("10+2=\n", fp);

    fclose(fp);
}

int calc(char ch, int a, int b)
{
    switch (ch)
    {
        case '/':
            return a / b;
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a *b;
        default:
            break;
    }
}

void read_file08()
{
    char buf[4096] = {0};
    char result[4096] = {0};

    char sum_res[4096] = {0};

    int a, b, ret;
    char ch;

    FILE *fp = fopen("test08.txt", "r");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }

    while (1)
    {
        fgets(buf, 4096, fp);  //buf = "10/2=\n\0";
        if (feof(fp))
        {
            break;
        }
        // 读取
        sscanf(buf, "%d%c%d=\n", &a, &ch, &b);
        // 格式打入字符串
        sprintf(result, "%d%c%d=%d\n", a, ch, b, calc(ch, a, b));  // 10 / 2 = 5;

        strcat(sum_res, result);
    }
    fclose(fp);

    fp = fopen("test08.txt", "w");
    if (fp == NULL)
    {
        perror("fopen error");
        return;
    }
    fputs(sum_res, fp);
    fclose(fp);
}


int main(void)
{
    write_file08();
    getchar();
    read_file08();

    system("pause");
    return EXIT_SUCCESS;
}      
  • 文件版排序
#include <iostream>


void  write_rand(){
    FILE *fp = fopen("test02.txt","w");
    if(!fp){
        perror("fopen error!");
        return ;
    }
    srand(time(NULL));
    for (size_t i = 0; i < 10; ++i) {
        fprintf(fp,"%d\n",rand()%100);
    }
    fclose(fp);
}
void BubbleSort(int * src, int len)
{
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = 0; j < len - 1 - i; j++)
        {
            if (src[j] > src[j + 1])
            {
                int temp = src[j];
                src[j] = src[j + 1];
                src[j + 1] = temp;
            }
        }
    }
}

void read_rand02(){
    int arr[10],i=0;
    FILE *fp = fopen("test02.txt","r");
    if(!fp){
        perror("fopen error!");
        return ;
    }
    while (1) {
        fscanf(fp, "%d\n", &arr[i]);
        i++;
        if (feof(fp)) {
            break;
        };
    }
    BubbleSort(arr, sizeof(arr)/sizeof(arr[0]));
    fclose(fp);
    fp = fopen("test02.txt", "w");
    if (!fp)  // fp == NULL
    {
        perror("fopen error");
        return ;
    }
    for (size_t i = 0; i < 10; i++) {
        fprintf(fp, "%d\n", arr[i]);
    }
    fclose(fp);
}


int main(void){
    write_rand();
    getchar();
    read_rand02();
    system("pause");
    return  EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

typedef struct student {
    int age;
    char name[10];
    int num;
} stu_t;
int write_struct()
{
    stu_t stu[4] = {
            18, "afei", 10,
            20, "andy", 20,
            30, "lily", 30,
            16, "james", 40
    };

    FILE *fp = fopen("test03.txt", "w");
    if (!fp)
    {
        perror("fopen error");
        return -1;
    }

    int ret = fwrite(&stu[0], 1, sizeof(stu_t) * 4, fp);
    if (ret == 0)
    {
        perror("fwrite error");
        return -1;
    }

    printf("ret = %d\n", ret);

    fclose(fp);
    return 0;
}
int read_struct()
{
    int i =0;
    FILE *fp = fopen("test03.txt", "r");
    if (!fp)
    {
        perror("fopen error");
        return -1;
    }
    stu_t s1[4];
    int ret = fread(&s1, 1, sizeof(stu_t)*4, fp);

//    printf("ret = %d\n", ret);
    for (i = 0; i < 4; ++i) {
        printf("age = %d, name=%s, num = %d\n", s1[i].age, s1[i].name, s1[i].num);
    }

    fclose(fp);
    return 0;
}

int read_struct2()
{
    FILE *fp = fopen("test03.txt", "r");
    if (!fp)
    {
        perror("fopen error");
        return -1;
    }
    stu_t s1[10];  // stu_t *s1 = malloc(sizeof(stu_t) * 1024);
    int i = 0;
    while (1)
    {
        int ret = fread(&s1[i], 1, sizeof(stu_t), fp);
        //if (ret == 0)
        if (feof(fp))
        {
            break;
        }
        i++;
        printf("age = %d, name=%s, num = %d\n", s1[i].age, s1[i].name, s1[i].num);
    }
    fclose(fp);
    return 0;
}

int main()
{
    write_struct();
    read_struct();
    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

void myfile_cp()
{
    FILE *rfp = fopen("test02.txt", "rb");
    FILE *wfp = fopen("mycopy.txt", "wb");

    char buf[4096] = {0};  //

    int ret = 0;

    while (1)
    {
//        memset(buf, 0, sizeof(buf));
        memset(buf,0, sizeof(buf));
        ret = fread(buf, 1, sizeof(buf), rfp);
        if (ret == 0)
        {
            break;
        }
        printf("ret = %d\n", ret);
        fwrite(buf, 1, ret, wfp);
    }
    fclose(wfp);
    fclose(rfp);
}

int main()
{
    myfile_cp();

    printf("---------------------finish\n");

    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

typedef struct student {
    int age;
    char name[10];
    int num;
} stu_t;
int main()
{
    stu_t stu[4] = {
            18, "afei", 10,
            20, "andy", 20,
            30, "lily", 30,
            16, "james", 40
    };
    stu_t s1;

    FILE *fp = fopen("test05.txt", "wb+");
    if (!fp)  // fp == NULL
    {
        perror("fopen error");
        return -1;
    }
    int ret = fwrite(&stu[0], 1, sizeof(stu), fp);  //
    printf("ret = %d\n", ret);
    fseek(fp, sizeof(stu_t)*2, SEEK_SET);       //
    ret = fread(&s1, 1, sizeof(s1), fp);
    printf("ret = %d\n", ret);

    printf("1 age= %d, name=%s, num=%d\n", s1.age, s1.name, s1.num);

    int len = ftell(fp); //

    printf("len = %d\n", len);

    rewind(fp); // ???????д????????????

    ret = fread(&s1, 1, sizeof(s1), fp);

    printf("2 age= %d, name=%s, num=%d\n", s1.age, s1.name, s1.num);

    //
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    printf("%d\n", len);

    fclose(fp);

    system("pause");
    return EXIT_SUCCESS;
}      
  • 随机读取文件
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

typedef struct student {
    int age;
    char name[10];
    int num;
} stu_t;

int main()
{
    FILE *fp = fopen("test0501.txt", "w+");  // "r+"

    int ret = fputs("11111", fp);
    printf("ret 1 = %d\n", ret);        // 0

    ret = fputs("22222", fp);
    printf("ret 2 = %d\n", ret);

    ret = fputs("33333", fp);
    printf("ret 3 = %d\n", ret);

    char buf[1024] = { 0 };

    //fseek(fp, 5 * 2, SEEK_SET);  //
    rewind(fp); //
    char *ptr = fgets(buf, 1024, fp);
    if (ptr == NULL)
        printf("ptr == NULL \n");

    printf("fgets ptr = %s\n", ptr);
    printf("buf = %s\n", buf);

    fclose(fp);
    system("pause");
    return EXIT_SUCCESS;
}      
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

typedef struct student {
    int age;
    char name[10];
    int num;
} stu_t;

int main()
{
    FILE *fp = fopen("test1.txt", "r+");

    char buf[6] = { 0 };
    char *ptr = fgets(buf, 6, fp);

    printf("buf=%s, ptr=%s\n", ptr, buf);

    fseek(fp, 0, SEEK_CUR);
    int ret = fputs("AAAAA", fp);
    printf("ret = %d\n", ret);

    fclose(fp);

    system("pause");
    return 0;
}      
  • 读取文件属性
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
    struct stat buf={0};
    int ret = stat("test05.txt", &buf);  //
    printf("%d\n", buf.st_size); //
    system("pause");
    return EXIT_SUCCESS;
}      
  • 刷新缓存区
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main()
{
    FILE *fp = fopen("test07.txt", "w+");
    if (!fp)
    {
        perror("fopen error");
        return -1;
    }
    char m = 0;

    while (1)
    {
        scanf("%c", &m);
        if (m == ':')
        {
            break;
        }
        fputc(m, fp);
        fflush(fp);
    }

    fclose(fp);

    system("pause");
    return EXIT_SUCCESS;
}      

继续阅读