2012-01-13 49 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