2012-01-13 50 views
-1

你好我想用一個文件輸入流或某種閱讀這樣的文字:閱讀本書在C/C++

E^@^@<a^[email protected]^@@^FÌø<80>è^AÛ<80>è ^F \^DÔVn3Ï^@^@^@^@ ^B^VÐXâ^@^@^B^D^E´^D^B^H 
IQRÝ^@^@^@^@^A^C^C^GE^@^@<^@^@@^@@^F.^K<80>è ^F<80>è^AÛ^DÔ \»4³ÕVn3Р^R^V J ^@^@^B^D^E´^D^B^H 
^@g<9f><86>IQRÝ^A^C^C^GE^@^@4a^[email protected]^@@^FÌÿ<80>è^AÛ<80>è ^F \^DÔVn3л4³Ö<80>^P^@.<8f>F^@^@^A^A^H 
IQRÞ^@g<9f><86>E^@^A±,[email protected]^@@^F^@E<80>è ^F<80>è^AÛ^DÔ \»4³ÖVn3Ð<80>^X^@.^NU^@^@^A^A^H 
^@g<9f><87> 

這是我試圖用讀它的代碼,但我得到了一堆爲0。

#include <stdio.h> /* required for file operations */ 

int main(int argc, char *argv[]){ 
    int n; 
    FILE *fr; 
    unsigned char c; 
    if (argc != 2) { 
    perror("Usage: summary <FILE>"); 
    return 1; 
    } 

    fr = fopen (argv[1], "rt"); /* open the file for reading */ 

    while (1 == 1){ 
    read(fr, &c, sizeof(c)); 
    printf("<0x%x>\n", c); 
    } 
    fclose(fr); /* close the file prior to exiting the routine */ 
} 

我的代碼出了什麼問題?我想我沒有正確讀取文件。

+0

什麼是文件的編碼? UTF8? Unicode的? – rkosegi 2012-01-13 05:34:08

+0

我不知道,你該怎麼做? – SuperString 2012-01-13 05:37:00

+0

等等,你使用'FILE *'並將它傳遞給'read()'? 'read()'需要一個'int fd',除非這是一個不是的平臺? – 2012-01-13 05:40:30

回答

2

你的沒編譯我,但我做了一些修正,它是正確的雨;-)

#include <stdio.h> /* required for file operations */ 

    int main(int argc, char *argv[]){ 
    int n; 
    FILE *fr; 
    unsigned char c; 
    if (argc != 2) { 
     perror("Usage: summary <FILE>"); 
     return 1; 
    } 

    fr = fopen (argv[1], "rt"); /* open the file for reading */ 

    while (!feof(fr)){ // can't read forever, need to stop when reading is done 
     // my ubuntu didn't have read in stdio.h, but it does have fread 
     fread(&c, sizeof(c),1, fr); 
     printf("<0x%x>\n", c); 
    } 
    fclose(fr); /* close the file prior to exiting the routine */ 
    } 
1

這看起來不像我的文字。因此,使用"r"模式至fopen,而不是"rt"

另外,^@代表'\0',所以你可能會在任何情況下讀一堆零。但不是全零。

+0

仍然是0嗎? – SuperString 2012-01-13 05:35:57

+0

你的文件有零個。使用'hexdump'或'xxd'轉儲文件。 – 2012-01-13 05:37:57

+0

hexdump/xxd ???? – SuperString 2012-01-13 05:42:09

3

您使用fopen()打開文件,它返回一個FILE *,並且read()閱讀它,這需要一個int。您需要一起使用open()read(),或者使用fopen()fread()。你不能將這些混合在一起。

爲了澄清,fopen()fread()化妝用的FILE指針,這是一種不同的方式來訪問和不同的抽象不是直線上升的文件描述符。 open()read()利用「原始」文件描述符,這是操作系統理解的概念。

雖然與此程序的失敗無關,但您的fclose()調用也必須匹配。換句話說,fopen(),fread()fclose()open(),read()close()

+0

我猜這是一個錯字,因爲代碼甚至不會像發佈一樣編譯。 'open'是一個未定義的標識符,因爲它的頭文件不包含在內,那麼參數將是錯誤的類型,不能被隱式轉換。 – 2012-01-13 05:46:12

+0

@BenVoigt:這可能是對的,現在你提到它。儘管如此,即使使用fread(),它也應該至少能夠正常工作並打印出適當的東西;它不會終止,'1 == 1'和全部。但是,你可能是對的。也許OP可以啓發我們。 – 2012-01-13 05:49:06