繁体   English   中英

读取一个充满整数的二进制文件,并以C的ASCII格式打印出来

[英]Read a binary file full of integers and print it out in an ASCII format in 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);

调用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)都表示部分读取,这可能是由于文件创建不正确造成的。

除非您有非常特殊的需求,否则您可能还需要重新考虑使用低级I / O函数(例如, openread ,它们实际上不是ISO C标准的一部分,并且您可以通过使用fopenfread基于流的功能。

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

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.
}

read函数返回实际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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM