1. 程式人生 > >73.fseek與寬字符讀取文件

73.fseek與寬字符讀取文件

nbsp rb+ col while 讀取 file pri spa fgetc

  • fseek
     1 //文件路徑
     2     char path[150] = "1.txt";
     3 
     4 
     5     //FILE *pf = fopen(path, "a+");//尾部添加,文件指針在尾部
     6     //FILE *pf = fopen(path, "w+");//文件指針在頭部,清空內容
     7     FILE *pf = fopen(path, "r+");//文件指針在頭部,不清空內容
     8     fseek(pf, 0, SEEK_END);
     9     fputs("0000000", pf);
    10     fflush(pf);//刷新文件
    11 
    12 
    13     //插入
    14     int
    length = 10; 15 for (int i = 0; i < 10;i++) 16 { 17 fseek(pf, -7-i-1, SEEK_END); 18 int ch = fgetc(pf); 19 //#define SEEK_CUR 1 當前 20 //#define SEEK_END 2 結束 21 //#define SEEK_SET 0 開頭 22 23 fseek(pf, -i-1, SEEK_END); 24 fputc(ch,pf); 25 fflush(pf);//
    刷新文件 26 } 27 fseek(pf, -17, SEEK_END);//a+ 文件指針移動無效 28 //r+,文件覆蓋 29 fputs("abcdefg", pf); 30 fflush(pf);//刷新文件 31 32 fclose(pf);

  • 以"rb+"的形式打開文件指針在頭部,不清空內容
     1     char path[150] = "1.txt";
     2     FILE *pf = fopen(path, "rb+");//文件指針在頭部,不清空內容
     3 
     4     fseek(pf, -20
    , SEEK_END);//a+ 文件指針移動無效 5 fputc(8, pf); 6 fputs("123545", pf); 7 8 rewind(pf); 9 10 char ch; 11 while ((ch=fgetc(pf))!=EOF) 12 { 13 putchar(ch); 14 } 15 16 fclose(pf);

  • 寬字符讀取文件
     1 //設定中文
     2     setlocale(LC_ALL, "zh-CN");
     3     wchar_t path[150] = L"Z:\\I\\百度內部員工聯系方式.txt";
     4     //文件指針在頭部,不清空內容
     5     FILE *pf = _wfopen(path, L"r");
     6     
     7     if (pf==NULL)
     8     {
     9         printf("error");
    10     }
    11     wchar_t wstr[1128] = { 0 };
    12     wchar_t *p = fgetws(wstr, 1128, pf);
    13     wprintf(L"-%s-\n", wstr);
    14     p = fgetws(wstr, 1128, pf);
    15     while (p!=NULL)
    16     {
    17         //輸出
    18         wprintf(L"-%s-\n", wstr);
    19         p = fgetws(wstr, 1128, pf);
    20     }
    21 
    22     fclose(pf);

73.fseek與寬字符讀取文件