读取一个完整的二进制文件,并在C中以ASCII格式打印出来

时间:2013-09-25 07:17:52

标签: c

我正在尝试接收一个充满4字节二进制整数的文件。我打开这个文件后试图使用read(),但根本无法弄清楚这个功能。我无法弄清楚如何格式化我的代码,我几乎找不到我想要做的这种特定类型的代码示例。我想读取一个完整的二进制文件,然后以ASCII格式打印每个整数。我还想在编写代码之前不知道二进制int的确切数量就能做到这一点。我一直在修改/尝试的一些片段是这样的,但我无法弄清楚如何将这样的东西实现到循环中。

char *infile = argv[1];
int fd = open(infile, O_RDONLY);

   int value;
   int rc = read(fd, &value, sizeof(int));
   printf("%d", value);

3 个答案:

答案 0 :(得分:2)

read的调用将返回读取的字节数,这样您就可以继续操作,直到获得所需大小以外的其他内容,例如:

ssize_t rc = read (fd, &value, sizeof value);
while (rc == sizeof value) {
    printf ("%d\n", value);
    rc = read (fd, &value, sizeof value);
}
if (rc == 0) {
    printf ("End of file reached okay\n");
} else if (rc < 0) {
    printf ("Some sort of error, errno = %d\n", errno);
} else {
    printf ("Only %d/%d bytes read\n", rc, sizeof value);
}

如您所见,从read收到的最终值决定了发生了什么。 -1表示某种错误,0表示已达到文件结尾,任何其他值(当然不是4)表示部分读取,可能是因为文件未正确创建。 / p>

您可能还想重新考虑使用低级I / O功能,例如openread,除非您有非常具体的需求,它们实际上并不是ISO C的一部分标准,您可以使用fopenfread基于流的函数实现相同的目标。

答案 1 :(得分:0)

你应该检查open的返回值,以及循环,直到read不再返回数据。这可能是因为文件已结束,或者是因为错误。

int rc, value;
while ((rc =  = read (fd, &value, sizeof(int)) != sizeof(int))
    printf ("%d\n", value);

if(rc == 0)
{
   // ok
}
else if(rc < 0)
{
   // error in errno.
   perror ("Read returned the following error:");   // perror will print an appropriate error message from errno.
}
else
{
    // file contains data which doesn't match up to a multiple of sizeof(int), so value may be undetermined here.
}

答案 2 :(得分:0)

read函数返回实际读取的字节数,如果发生错误则返回-1,如果到达文件末尾则返回0,因此即使您不知道也可以使用它来读取所有整数有多少人。

因此,使用read,您的代码可能是这样的:

char *infile = argv[1];
int fd = open(infile, O_RDONLY);

int value;
int rc;
while ((rc = read(fd, &value, sizeof(int)) > 0) {
    printf("%d\n", value);
}

使用fopen / fread(推荐):

char *infile = argv[1];
FILE *fp = fopen(infile, "r");

int value;
int rc;
while ((rc = fread(&value, sizeof(int), 1, fp) > 0) {
    printf("%d\n", value);
}

请注意freadread略有不同,第二个参数是每个值的大小,第三个参数是您想要读取的值。它将返回它实际读取的值(不是字节数)(在这种情况下,当有值要读取时,它将为1)。

另外值得一提的是,你说要读取4个字节的值。在大多数现代平台中,Int是4个字节,但是没有保证,如果你想确保它总是4个字节,请包含标题<stdint.h>并使用int32_t