Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Read()系统调用读取结构内容 #包括“common.h” #包括 结构缓冲区 { 国际贸易编号; 字符名[20]; }; int main() { 结构缓冲区buf; 结构缓冲区读取; int-fd; 如果((fd=open(“read_write.txt”,O|u RDWR,S|IRUSR | S|IWUSR))_C_Linux_Struct - Fatal编程技术网

使用Read()系统调用读取结构内容 #包括“common.h” #包括 结构缓冲区 { 国际贸易编号; 字符名[20]; }; int main() { 结构缓冲区buf; 结构缓冲区读取; int-fd; 如果((fd=open(“read_write.txt”,O|u RDWR,S|IRUSR | S|IWUSR))

使用Read()系统调用读取结构内容 #包括“common.h” #包括 结构缓冲区 { 国际贸易编号; 字符名[20]; }; int main() { 结构缓冲区buf; 结构缓冲区读取; int-fd; 如果((fd=open(“read_write.txt”,O|u RDWR,S|IRUSR | S|IWUSR)),c,linux,struct,C,Linux,Struct,我已经在文件中写入了一个结构。但我对如何检索之前写入对象“read_buf”的结构的每个元素感到困惑。请告诉我怎么做 谢谢你这样回读: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> char errorbuf[20]; #d

我已经在文件中写入了一个结构。但我对如何检索之前写入对象“read_buf”的结构的每个元素感到困惑。请告诉我怎么做


谢谢你这样回读:

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

char errorbuf[20];

#define PRINT_ERROR(errorbuf) \
   do \
   { \
      sprintf(errorbuf,"%s:%d",__FILE__,__LINE__); \
      perror(errorbuf); \
      exit(-1); \
   }while(0);
这会起作用,但还有一些事情你必须担心

  • 这不是便携式的
  • 您将不得不担心不同构建上的结构打包
  • 您将在跨平台时遇到endian问题
  • Windows您可能需要O_二进制文件

几乎总是最好将结构重新打包为已知格式(具有已知的结尾),以便可靠地读回数据。

在文件中写入/读取二进制结构是不可移植的(取决于平台架构、结构填充等)。要使程序健壮,可以使用类似的方法。

我做了类似的操作。但是当我打印buf.no时,我得到了垃圾值。当我打印buf.name时,在使用
lseek(fd,0,SEEK_SET)
读取之前,我没有得到任何重新打开或回放文件。谢谢,我错过了lseek:)我得到了…:)我错过了“写入”和“读取”之间的“lseek”。这就是为什么我在阅读文件时总是收到垃圾邮件的原因。谢谢
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

char errorbuf[20];

#define PRINT_ERROR(errorbuf) \
   do \
   { \
      sprintf(errorbuf,"%s:%d",__FILE__,__LINE__); \
      perror(errorbuf); \
      exit(-1); \
   }while(0);
ssize_t bytes_read = read(fd, &buf, sizeof buf);
if(-1 == bytes_read)
    ; // handle read error
if(sizeof buf != bytes_read)
    ; // handle incomplete read
lseek(fd,0,SEEK_SET);
read(fd,&buf,sizeof(struct buffer);