1. 程式人生 > >2. C語言文件操作經典習題

2. C語言文件操作經典習題

main pri 多少 linux 文件操作 spa 加密文件 include 加密

1. 統計英文文本文件中,有多少個大寫字母、小寫字母、數字、空格、換行以及其他字符。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

void main()
{
    char path[100] = "c:\\統計.txt";
    FILE *fp;                 //創建文件指針
    fp = fopen(path, "r");    //打開文件,按照讀的模式
    
    if (fp == NULL)
    {
        printf(
"文件打開失敗!\n"); return; } else { char ch; int countBig = 0; //統計大寫字母的個數 int countSmall = 0; //統計小寫字母的個數 int contNum = 0; //統計數字的個數 int countEnter = 0; //統計換行的個數 int countSpace = 0; //統計空格的個數 int countOther = 0; //統計其他字符的個數
while ((ch = fgetc(fp)) != EOF) //獲取一個字符,沒有結束就繼續 { if (ch >= A&&ch <= Z) //判斷是否大寫字母 countBig++; else if (ch >= a&&ch <= z) //判斷是否小寫字母 countSmall++; else if (ch >=
0&&ch <= 9) //判斷是否數字 contNum++; else if (ch == \n) //判斷是否換行 countEnter++; else if (ch == ) //判斷是否空格 countSpace++; else //其他字符 countOther++; } printf("大寫字母:%d, 小寫字母:%d, 數字:%d, 換行:%d, 空格:%d, 其他:%d\n", countBig, countSmall, contNum, countEnter, countSpace, countOther); } fclose(fp); system("pause"); }

2. 編程實現搜索文件

  Windows下:

  遍歷所有c盤下所有 *.txt *.exe dir.* :

    for /r c:\ %i in (*.txt) do @echo %i

  在c盤下搜索所有文件內容包含 hello 的文件:

    for /r c:\ %a in (*) do @findstr /im "hello" "%a"

  Linux下:(搜索時進入管理員權限)

  指定目錄搜索----確定文件名:

    find /etc -name 1.c

  搜索文件名中帶c的文件:

    find / -name *c*

  從根目錄開始查找所有擴展名為 .log 的文本文件,並找出包含“ERROR” 的行:

    find / -type f -name "*.log" | xargs grep "ERROR"

  Windows下代碼如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

void main()
{
    /*按文件名進行搜索*/
    //char path[100] = "C:\\Users\\Administrator\\Desktop";                //搜索用的目錄
    ////搜索文件名用的通配符 *.txt表示所有文本文件
    ////1.*表示1開頭的所有文件,*.*表示所有文件
    //char fileName[30] = "*.txt";
    //char outputPath[100] = "c:\\";            //保存輸出結果的文件
    //char cmd[512];
    ////for /r "%s" %i in (%s) do @echo %i >> "%s",path, fileName, outputPath
    //sprintf(cmd, "for /r \"%s\" %%i in (%s) do @echo %%i >> \"%s\"", path, fileName, outputPath);    //打印字符串
    //system(cmd);                            //執行查找,並將結果輸入到outputPath這個文件

    //char showCmd[200];
    //sprintf(showCmd, "type %s", outputPath);//打印字符串,便於查看
    //system(showCmd);                        //顯示


    /*按文件內容進行搜索*/
    char path[100] = "C:\\Users\\Administrator\\Desktop";
    char str[20] = "hello";
    char cmd[500];
    char output[100] = "C:\\Users\\Administrator\\Desktop\\output.txt";    //保存輸出結果的文件
    //創建一個指令字符串,按照一段文本,在一個目錄下檢索所有包含了這段文本的文件
    sprintf(cmd, "for /r %s %%a in (*) do @findstr /im \"%s\" \"%%a\" >> %s", path, str, output);
    system(cmd);    //執行指令 

    char showCmd[200];
    sprintf(showCmd, "type %s", output);//打印字符串,便於查看
    system(showCmd);                    //顯示

    system("pause");
}

  Linux下代碼如下:

#include <stdio.h>
#include <stdlib.h>

void main()
{
    /*按文件名進行搜索*/
    //char str[20] = "*c*";
    //char path[100] = "/home";
    //char output[100] = "/home/output.txt";
    //char cmd[100];
    //sprintf(cmd, "find %s -name \‘%s\‘ >> %s", path, str,output);
    //ystem(cmd);

    //char show[100];
    //sprintf(show, "cat %s", output);
    //system(show);


    /*按文件內容進行搜索*/
    char path[100] = "/home";
    char str[20] = "hello";
    char findName[20] = "*.c";
    char output[100] = "/home/output.txt";
    char cmd[100];
    char show[100];
    sprintf(cmd, "find %s -type f -name \"%s\" |  xargs grep %s >> %s", path, findName, str,output);
    system(cmd);

    sprintf(show, "cat %s", output);
    system(show);
}

3. 統計文本文件中有多少個漢字。

  GBK(漢字編碼標準)規定,漢字,日文,韓文第一個字節大於128

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

void main()
{
    FILE *fp;                            //空的文件指針
    char path[100] = "c:\\1.txt";        //文件路徑
    fp = fopen(path, "r");               //讀的方式打開文件
    
    if (fp == NULL)
        perror("文件打開失敗原因是:");      //輸出錯誤原因

    int ich;                   //獲取字符,fgetc的返回值是int,不用int,ASCII碼沒有問題,但是漢字會出問題
    //int占4個字節,用int才能存儲漢字的編碼,而char裝不下
    int countEng=0;            //標記英文字符
    int countNum=0;            //標記數字
    int countChin=0;           //標記漢字

    while ((ich = fgetc(fp)) != EOF)
    {
        if ((ich >= A&&ich <= Z) || (ich >= a&&ich <= z))
            countEng++;        //字母自增
        else if (ich >= 0&&ich <= 9)
            countNum++;        //數字自增
        else if (ich > 128)    //判斷雙字節字符
        {
            //此處僅得到了雙字節,還需要增加判斷漢字的代碼(GBK編碼規範)。。。此處省略
            ich = fgetc(fp);   //繼續向前讀一個字符
            countChin++;       //雙字符自增
        }
    }

    printf("英文字符%d,  數字%d,  雙字節字符%d\n", countEng, countNum, countChin);

    fclose(fp);
    system("pause");
}

4. 文件加密和解密。

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

//1.txt加密後保存到1-Encrypt.txt;解密以後保存到1-Decrypt.txt
//加密最好按照二進制的方式加密,可以保證絕對精確
//文本的方式,換行符會被解析為/r/n,往往容易出現問題
//加密
void Encrypt(int passwd)
{
    FILE *fpr;    //讀取1.txt
    FILE *fpw;    //寫入1-Encrypt.txt
    char pathr[100] = "c:\\1.txt";
    char pathw[100] = "c:\\1-Encrypt.txt";

    fpr = fopen(pathr, "r");    //讀的模式打開需要加密的文件
    fpw = fopen(pathw, "w");    //寫的模式打開要寫入的加密文件

    if (fpr == NULL || fpw == NULL)
    {
        printf("文件故障,加密失敗!\n");
        return;
    }

    while (!feof(fpr))            //一直讀到要加密的文件末尾
    {
        char ch = fgetc(fpr);    //讀取文本

        /*字符移位加密*/
        //ch = ch + passwd;

        /*異或加密*/
        ch = ch^passwd;

        fputc(ch, fpw);            //寫入文件
    }

    fclose(fpr);
    fclose(fpw);
}

//解密
void Decrypt(int passwd)    //傳入數組,傳入長度
{
    FILE *fpr;    //讀取1-Encrypt.txt
    FILE *fpw;    //寫入1-Decrypt.txt
    char pathr[100] = "c:\\1-Encrypt.txt";
    char pathw[100] = "c:\\1-Decrypt.txt";

    fpr = fopen(pathr, "r");    //讀的模式打開加密後的文件1-Encrypt.txt
    fpw = fopen(pathw, "w");    //寫的模式打開解密後要寫入的文件1-Decrypt.txt

    if (fpr == NULL || fpw == NULL)
    {
        printf("文件故障,加密失敗!\n");
        return;
    }

    while (!feof(fpr))            //一直讀到要解密的文件末尾
    {
        char ch = fgetc(fpr);     //讀取文本

        /*字符移位解密*/
        //ch = ch - passwd;

        /*異或解密*/
        ch = ch^passwd;
        
        fputc(ch, fpw);            //寫入文件
    }

    fclose(fpr);
    fclose(fpw);
}

void Encrypt_str(int passwd[], int len)
{
    FILE *fpr;    //讀取1.txt
    FILE *fpw;    //寫入1-Encrypt.txt
    char pathr[100] = "c:\\1.txt";
    char pathw[100] = "c:\\1-Encrypt.txt";

    fpr = fopen(pathr, "rb");    //讀的模式打開需要加密的文件    二進制加解密最精準
    fpw = fopen(pathw, "wb");    //寫的模式打開要寫入的加密文件

    if (fpr == NULL || fpw == NULL)
    {
        printf("文件故障,加密失敗!\n");
        return;
    }

    int i = 0;            //標識取出加密數組的哪一位
    while (!feof(fpr))           //一直讀到要加密的文件末尾
    {
        char ch = fgetc(fpr);    //讀取文本

        /*字符移位加密*/
        //ch = ch + passwd;

        /*異或加密*/
        //ch = ch^passwd;

        /*字符串移位加密*/
        if (i > len - 1)        //如果加密數組完成,就繼續重新開始
            i = 0;
        ch = ch + passwd[i];
        i++;                    //用完這個數組當前字符,移動到下一個字符

        fputc(ch, fpw);         //寫入文件
    }

    fclose(fpr);
    fclose(fpw);
}

void Decrypt_str(int passwd[], int len)
{
    FILE *fpr;    //讀取1-Encrypt.txt
    FILE *fpw;    //寫入1-Decrypt.txt
    char pathr[100] = "c:\\1-Encrypt.txt";
    char pathw[100] = "c:\\1-Decrypt.txt";

    fpr = fopen(pathr, "rb");    //讀的模式打開加密後的文件1-Encrypt.txt
    fpw = fopen(pathw, "wb");    //寫的模式打開解密後要寫入的文件1-Decrypt.txt

    if (fpr == NULL || fpw == NULL)
    {
        printf("文件故障,加密失敗!\n");
        return;
    }

    int i = 0;
    while (!feof(fpr))            //一直讀到要解密的文件末尾
    {
        char ch = fgetc(fpr);    //讀取文本

        /*字符移位解密*/
        //ch = ch - passwd;

        /*異或解密*/
        //ch = ch^passwd;

        /*字符串移位解密*/
        if (i > len - 1)        //如果加密數組完成,就繼續重新開始
            i = 0;
        ch = ch - passwd[i];
        i++;                    //用完這個數組當前字符,移動到下一個字符

        fputc(ch, fpw);            //寫入文件
    }

    fclose(fpr);
    fclose(fpw);
}

void main()
{
    /*字符移位加密*/
    //Encrypt();
    //Decrypt();

    //Encrypt(6);
    //Decrypt(6);

    /*異或加密*/
    //Encrypt(15);
    //Decrypt(15);

    /*字符串移位加密*/
    char passwd[] = "helloworld";
    int n = strlen(passwd);
    Encrypt_str(passwd, n);
    Decrypt_str(passwd, n);

    system("pause");
}

5. 文件的分割與合並。

  分割文件:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

//文件切割
void main()
{
    char path[100] = "c:\\1-文件分割與合並";      //文件夾路徑
    char filename[50] = "test.mp4";             //文件名
    char lastpath[150];                         //存儲文件的路徑
    sprintf(lastpath, "%s\\%s", path, filename);//構建文件的路徑

    int filesize = 0;                           //獲取文件的大小
    FILE *fpr = fopen(lastpath, "rb");          //二進制讀入的方式打開
    
    if (fpr == NULL)
    {
        perror("文件打開失敗,原因是:");
        return;
    }

    fseek(fpr, 0, SEEK_END);                  //文件指針移動到末尾
    filesize = ftell(fpr);                    //獲取文件指針與開頭有幾個字節
    printf("文件有%d個字節\n", filesize);
        
    int setsize = 1024 * 1024;                //設置要分割的模塊大小
    int N;                                    //存儲一個文件最多可以分割為多少個模塊
    if (filesize%setsize == 0)
        N = filesize / setsize;
    else
        N = filesize / setsize + 1;

    fseek(fpr, 0, SEEK_SET);                  //文件指針移動到開頭
    char listpath[100] = "c:\\1-文件分割與合並\\list.txt";
    FILE *fplist = fopen(listpath, "w");      //創建list.txt文件

    for (int i = 1; i <= N; i++)              //針對每一塊進行處理
    {
        char temppath[120];                   //存儲每一塊的路徑
        sprintf(temppath, "%s\\%d%s", path, i, filename);//構建每一塊的文件名
        printf("%s\n", temppath);             //顯示路徑
        fputs(temppath, fplist);              //每一塊的路徑寫入list.txt
        fputc(\n, fplist);                  //寫入換行符

        FILE *fpb = fopen(temppath, "wb");    //按照二進制寫入的模式打開文件
        if (i < N)
        {
            for (int j = 0; j < setsize; j++)                    //前面N-1個都是完整的
            {
                int ich = fgetc(fpr);        //讀取一個字符
                fputc(ich, fpb);             //寫入一個字符
            }
        }
        else
        {
            for (int j = 0; j < filesize-(N-1)*setsize; j++)    //最後一個不完整
            {
                int ich = fgetc(fpr);        //讀取一個字符
                fputc(ich, fpb);             //寫入一個字符
            }
        }
        fclose(fpb);                         //關閉寫入的塊文件
    }

    fclose(fplist);    //關閉列表文件
    fclose(fpr);       //關閉讀取的文件
    system("pause");
}

  文件合並:

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

//文件合並
void main()
{
    char path[100] = "c:\\1-文件分割與合並\\list.txt";            //文件夾路徑
    FILE *fpr = fopen(path, "r");                               //讀的方式打開
    char allpath[100] = "c:\\1-文件分割與合並\\test-all.mp4";     //合並後的文件
    FILE *fpw = fopen(allpath, "wb");    //按照二進制寫入的方式打開合並的文件
    char temppath[200];
    while (fgets(temppath, 200, fpr))    //不斷循環地獲取路徑,fgets讀到字符串值為非0;讀不到或到末尾值為0
    {
        printf("%s", temppath);          //字符串有換行符
        int len = strlen(temppath);      //取出字符串長度
        temppath[len - 1] = \0;        //換行符替換為‘\0’
        {
            FILE *fpb = fopen(temppath, "rb");       //按照二進制讀取的方式打開文件
            int ich = fgetc(fpb);                    //讀取一個字符
            while (!feof(fpb))           //沒有到文件結束就繼續
            {
                fputc(ich, fpw);         //寫入要合並的文件
                ich = fgetc(fpb);
            }
            fclose(fpb);                //結束讀取
        }

    }

    fclose(fpw);    //關閉要合並的文件的文件指針
    fclose(fpr);    //關閉list.txt的文件指針
    system("pause");
}

2. C語言文件操作經典習題