我在Windows 8.1中使用MinGW,並且我有一個原始數字輸入文本文件(每行一個),我想在二進制文件中將它們編寫爲二進制文件。這個例子是沒有問題的編譯具有:fread或fwrite給出「Bad file number」
gcc -pedantic -Os -c my_code.c -o my_code.exe
但輸出
$ my_code.exe
sh: ./my_code.exe: Bad file number
這是我寫的代碼:
#include<stdio.h>
int main()
{
FILE *fp;
FILE *prob;
int length;
char buffer[30];
// Open file containing numbers
if ((prob = fopen("raw_numbers.txt","r")) == NULL)
{
printf("Could not open raw_numbers.txt\n");
exit(1);
}
/* Create output binary file */
fp = fopen("file.bin" , "w");
while(! feof(prob))
{
fgets(buffer, sizeof(buffer), prob);
fwrite((const void*) & buffer, 1, sizeof(buffer), fp);
}
fclose(prob);
fclose(fp);
return(0);
}
使用
$ gcc --version
gcc (GCC) 3.4.4 (msys special)
我覺得你應該通過'buffer',而不是'&buffer'到使用fwrite。 – squirem
仍然錯誤的文件編號依然存在& – Veronica
您必須檢查文件'file.bin'是否已經真正打開。 – DaBler