c function: feof()
這幾天同是寫的小程式有問題,程式的功能只是簡單的開檔、讀檔、寫入檔案。
程式碼如下,使用dev c++ 4.9.9.2環境。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *pFile, *myFile;
size_t result;
char c = 0;
if(1)
{
// pFile = fopen(argv[1], "r");
pFile = fopen("xxx.dfi", "rb");
// rewind (pFile);
if (pFile != NULL)
{
myFile = fopen("1.txt", "wb");
if (myFile != NULL)
{
while(fread(&c, sizeof(char), 1, pFile))
//while(!feof(pFile))
//while(((c = fgetc(pFile)) != " "))
{
//fscanf(pFile, "%c", &c);
fwrite(&c, sizeof(char), 1, myFile);
//fprintf(myFile, "%c", c);
}
}
else
{
printf("Fail to open file 1.txt\r\n");
}
fclose(pFile);
}
else
printf("Fail to open file %s\r\n", argv[1]);
}
else
{
printf("The parameters are not correct! transformBin.exe [INPUT_FILE] [OUTPUTFILE]\r\n");
}
fclose(myFile);
system("PAUSE");
return 0;
}
在使用feof()這個API的時候發現最後檔案會多一個byte,我的環境下這個byte是0x00,後來稍微研究了一下 feof這個API發現在C語言中,feof()這個API雖然是檢察是否到達檔案的尾端,但是其檢查方式比較笨,他是在讀取的時候發現是EOF,此時再call feof()才會發覺到是檔尾,因此會多出一個byte來是程式碼中前一個c的value。也就是迴圈被多做了一次。
改正的方式就是直接驗證每次讀回來的值是否能讀到來做為檔案尾端的依據,因為二進位檔案無法使用和EOF相比來做判斷(text檔案不會有負值,但是二進位檔可以,因此會造成誤判)
另外
fread() fwrite()是用在二進位檔案的讀寫
fscanf() fprintf()是用在文件檔案的讀寫
程式碼如下,使用dev c++ 4.9.9.2環境。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *pFile, *myFile;
size_t result;
char c = 0;
if(1)
{
// pFile = fopen(argv[1], "r");
pFile = fopen("xxx.dfi", "rb");
// rewind (pFile);
if (pFile != NULL)
{
myFile = fopen("1.txt", "wb");
if (myFile != NULL)
{
while(fread(&c, sizeof(char), 1, pFile))
//while(!feof(pFile))
//while(((c = fgetc(pFile)) != " "))
{
//fscanf(pFile, "%c", &c);
fwrite(&c, sizeof(char), 1, myFile);
//fprintf(myFile, "%c", c);
}
}
else
{
printf("Fail to open file 1.txt\r\n");
}
fclose(pFile);
}
else
printf("Fail to open file %s\r\n", argv[1]);
}
else
{
printf("The parameters are not correct! transformBin.exe [INPUT_FILE] [OUTPUTFILE]\r\n");
}
fclose(myFile);
system("PAUSE");
return 0;
}
在使用feof()這個API的時候發現最後檔案會多一個byte,我的環境下這個byte是0x00,後來稍微研究了一下 feof這個API發現在C語言中,feof()這個API雖然是檢察是否到達檔案的尾端,但是其檢查方式比較笨,他是在讀取的時候發現是EOF,此時再call feof()才會發覺到是檔尾,因此會多出一個byte來是程式碼中前一個c的value。也就是迴圈被多做了一次。
改正的方式就是直接驗證每次讀回來的值是否能讀到來做為檔案尾端的依據,因為二進位檔案無法使用和EOF相比來做判斷(text檔案不會有負值,但是二進位檔可以,因此會造成誤判)
另外
fread() fwrite()是用在二進位檔案的讀寫
fscanf() fprintf()是用在文件檔案的讀寫
留言
張貼留言