c - 使用 unistd.h 读取和写入结构读/写

标签 c unix

我正在学习 UNIX 编程,并正在尝试读/写系统调用。 我有一个包含一对整数的文件:

4 5

我编写了这段代码来读取数字:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

typedef struct prova {
    int first;
    int second;
} prova_t;

int main(void) {
    int fd;
prova_t origin;
prova_t result;
ssize_t bytes_read;
size_t nbytes;

fd = open("file.bin", O_WRONLY | O_CREAT);
origin.first = 24;
origin.second = 3;
write(fd, &origin, sizeof(prova_t));
close(fd);


fd = open("file.bin", O_RDONLY);
nbytes = sizeof(prova_t);
/* 1.BAD */
bytes_read = read(fd, &result, nbytes);
write(STDOUT_FILENO, &(result.first), sizeof(int));
write(STDOUT_FILENO, &(result.second), sizeof(int));
close(fd);

    /* 2.GOOD */
    nbytes = sizeof(int);
    bytes_read = read(fd, &(result.first), nbytes);
    write(STDOUT_FILENO, &(result.first), bytes_read);
    bytes_read = read(fd, &(result.second), nbytes);
    write(STDOUT_FILENO, &(result.second), bytes_read);

    return 0;
}

在我的第一次尝试中,我尝试从文件中读取整个结构并将其成员写入标准输出。这样,除了数字之外,我还得到了一些奇怪的字符

4 5
E�^�

在第二次尝试中,我一一读取了数字,输出没有任何问题。

有没有办法使用第一种方法来读写结构体?

编辑:我更新了代码以反射(reflect)其他用户的建议,但仍然得到奇怪的字符而不是数字

最佳答案

首先,让我们进行十六进制转储以查看文件中实际存储的内容。

hexdump -C b.txtod -t x2 -t c b.txt 是两个示例(od 表示八进制转储,更常见,但输出不太漂亮我的意见)

00000000  34 20 35 0a                                       |4 5.|
00000004

这就是文件创建为 ASCII 文本文件时的样子(例如使用 vi 等文本编辑器)。您可以使用 man ascii 来仔细检查十六进制值。

现在,如果您有一个仅包含两个 8 位字节的二进制文件,按照系统的 native 字节顺序(例如 x86 的小端序,MIPS、PA-RISC、680x0 的大端序),那么十六进制转储将如下所示:

00000000  04  05                                            |..|
00000004

这是创建(打开和写入)二进制文件并将其读回的代码。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>     /* uint32_t */
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

/* User has read & write perms, group and others have read permission */ 
const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

typedef struct prova {
   uint32_t first;
   uint32_t second;
} prova_t;

#define FILENAME "file.b"

/* 'Safe' write */
int safewrite( int fd, const void *p, size_t want) {
   int ret;

   errno = 0;
   while (want) {
      ret = write(fd, (uint8_t *)p, want);
      if (ret <= 0) {
         if (errno != EINTR && errno != EAGAIN) {
            return -1;
         }
         errno = 0;
         continue;
      }
      want -= ret;
      p = (uint8_t*) p + ret;
   }
   return 0;
}

int saferead(int fd, const void *p, size_t want) {
   int ret;

   errno = 0;
   while (want) {
      ret = read(fd, (uint8_t*)p, want);
      if( ret == 0 )
         return -1;  /* EOF */
      if (ret <= 0) {
         if( errno != EINTR && errno != EAGAIN ) {
            return -1;
         }
         errno = 0;
         continue;
      }
      want -= ret;
      p = (uint8_t*) p + ret;
   }
   return 0;
}


int main(int argc, char **argv) {
   int fd;
   prova_t result;
   size_t nbytes;

   /* Create file */
   fd = creat(FILENAME, mode);
   if (fd < 0) {
      fprintf(stderr, "Unable to open " FILENAME ": %s\n",
            strerror(errno));
      exit(EXIT_FAILURE);
   }
   nbytes = sizeof(prova_t);

   result.first = 4;
   result.second = 5;

   if (0 != safewrite(fd, &result, nbytes)) {
      fprintf(stderr, "Unable to write to " FILENAME ": %s\n",
            strerror(errno));
      exit(EXIT_FAILURE);
   }

   close(fd);
   fd = -1;

   /* Reopen and read from binary file */
   fd = open(FILENAME, O_RDONLY);
   nbytes = sizeof(prova_t);

   if (0 != saferead(fd, &result, nbytes)) {
      fprintf(stderr, "Unable to read file \"" FILENAME "\": %s\n",
            strerror(errno));
      exit(EXIT_FAILURE);
   }
   close(fd);

   printf( "Read: %d %d (%#.02x%.02x)\n",
         result.first, result.second,
         result.first, result.second);

   return EXIT_SUCCESS;
}

现在数据文件内容如下所示:

00000000  04 00 00 00 05 00 00 00                           |........|
00000008

因为整数被指定为 32 位整数(32 位/每字节 8 位 = 4 字节)。我使用的是 64 位系统(little endian,x86),因此我想明确一点,以便您的结果应该匹配(假设是little-endian)。

关于c - 使用 unistd.h 读取和写入结构读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146897/

相关文章:

c++ - c/c++中指针的内存开销

bash - grep命令知道两个字符串是否按特定顺序

linux - 如何在 bash 中启动读写进程?

c - 在C中从void *转换为char **

c++ - 运行涉及 struct tm 的 C++ 程序的 Unix 错误

c++ - FFmpeg:如何在不重新编码的情况下将编码的媒体数据从一个容器放入另一个容器?

c - 如何输入两个中间有破折号的整数?

c - 如何重新打开一个关闭的文件描述符

C、功能太长不规范

c - msgsnd 无权限错误