天天看點

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;
}      

繼續閱讀