2016-10-04 62 views
0

我在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) 
+3

我覺得你應該通過'buffer',而不是'&buffer'到使用fwrite。 – squirem

+0

仍然錯誤的文件編號依然存在& – Veronica

+2

您必須檢查文件'file.bin'是否已經真正打開。 – DaBler

回答

4

你有多個錯誤rs在您的程序中:

  • 您應該測試未能創建輸出文件。

  • 你應該測試,而不是使用while (!feof())...fgets()的返回值,這不會做你認爲在Why is 「while (!feof (file))」 always wrong?

  • 解釋你應該通過bufferfwrite而不是&buffer

  • 你應該傳遞要寫入的字節數(strlen(buffer))而不是緩衝區的大小。

  • 你說輸出文件應該是二進制的,但你打開它作爲文本文件並寫入文本。你是否想將數字轉換爲二進制並寫入二進制表示?

這裏是另一種實現上述:

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

int main(void) { 
    FILE *fp; 
    FILE *prob; 
    int value; 
    char buffer[30]; 

    /* Open file containing numbers */ 
    if ((prob = fopen("raw_numbers.txt", "r")) == NULL) { 
     printf("Could not open raw_numbers.txt: %s\n", strerror(errno)); 
     exit(1); 
    } 

    /* Create output binary file */ 
    if ((fp = fopen("file.bin", "wb")) == NULL) { 
     printf("Could not open file.bin: %s\n", strerror(errno)); 
     exit(1); 
    } 

    while (fgets(buffer, sizeof(buffer), prob) != NULL) { 
     value = atoi(buffer); 
     if (fwrite(&value, sizeof(value), 1, fp) != 1) { 
      printf("Error writing to file.bin: %s\n", strerror(errno)); 
      exit(1); 
     } 
    } 

    fclose(prob); 
    fclose(fp); 
    return 0; 
} 

外殼診斷是誤導性的,但在這裏的意思是這樣:文件my_code.exe有一個簽名(也被稱爲神奇數字)不被識別爲可執行文件。內核無法確定如何從其幻數中運行該文件,因此錯誤的文件號

原因是您的編譯命令:gcc -pedantic -Os -c my_code.c -o my_code.exe將源文件my_code.c編譯爲對象格式,而不是直接鏈接到可執行格式。刪除-c選項來編譯和鏈接一步到位:

gcc -pedantic -Os my_code.c -o my_code.exe 
+0

「你是不是要將數字轉換爲二進制並寫入二進制表示?」是!!這正是我想要的。但是你的代碼在執行時也返回壞文件編號。 – Veronica

+0

@Veronica:看到我關於神祕的shell錯誤消息的更新回答......這個很棘手! – chqrlie