【发布时间】:2014-11-07 18:40:21
【问题描述】:
我正在尝试编写一个程序,我可以将int 复制到char 数组中,然后使用write 系统调用将该char 数组写入文件。在另一个程序中,我想将文件的内容读入char 数组,然后从数组中检索int。我无法理解的是如何将int 的内容写入数组以及如何从char 数组中读取int。
这就是我所拥有的
写入文件:
int fd2 = open("file2.txt", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);
//create buff2 with 1024 chars and last 4 bytes as int
write(fd2, buff2, 1028);
我不确定如何准确实现注释行
从文件中读取:
int fd2 = open("file2.txt", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);
char buff2[1028];
read(fd2, buff2, 1028);
int val = *((int)((buff2+1023)+sizeof(int))); // file contains exactly 1028 bytes. first 1024 are characters, next 4 is int
printf("%d\n", val);
我试图读取整数的行给了我一个编译器错误,说invalid type argument of unary '*' (have 'int')
如果有任何帮助,我将不胜感激
【问题讨论】:
-
write(fd2, &my_int, sizeof(int))和read(fd2, &my_int, sizeof(int))有什么问题?