我是新人。我有一些问题,任何帮助将不胜感激。 我有一个结构,并使用write()将其写入文件。
struct PointFull {
double lat;
double lon;
};
PointFull item;
void* buffer = malloc(sizeof (item));
int fd = open("output", O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR);
if (fd < 0) {
printf("Error opening file\n");
return 1;
}
memcpy(buffer, &item, sizeof (item));
write(fd2, buffer, sizeof (item));
现在我有一个名为&#34;输出&#34;在硬盘然后我想读取文件来测试数据。
int fd2 = open("output", O_RDONLY, S_IWUSR | S_IRUSR);
if (fd2 < 0) {
printf("Error opening file\n");
return 1;
}
void* bufferRead;
bufferRead = malloc(100);
read(fd2, bufferRead,100);
目前,我有bufferRead但我不知道如何读取缓冲区以将数据插入到struct ???任何帮助将不胜感激。
答案 0 :(得分:1)
因为你已经标记了C ++
#include <iostream>
#include <fstream>
using namespace std;
struct PointFull {
double lat;
double lon;
PointFull(double lat_in = 0, double lon_in = 0)
: lat(lat_in), lon(lon_in) {}
};
int main() {
PointFull item(123123, 123123);
cout << "Writing to disk" << endl;
ofstream fout("saved_point.txt");
fout << item.lat << ' ' << item.lon;
fout.close();
cout << "Reading from disk" << endl;
PointFull item_from_disk;
ifstream fin("saved_point.txt");
fin >> item_from_disk.lat >> item_from_disk.lon;
fin.close();
cout << "From RAM and then disk" << endl;
cout << item.lat << ' ' << item.lon << endl;
cout << item_from_disk.lat << ' ' << item_from_disk.lon << endl;
return 0;
}
答案 1 :(得分:1)
您宁愿分配大小为sizeof(PointFull)
的缓冲区。因为如果结构的大小会被改变并且变得比你的硬编码大,那么你将会得到一个错误。
除非确实需要使用动态内存,否则请使用本地缓冲区。我认为在你的代码中你并不需要分配。只是你可能很容易忘记释放内存,而缓冲区在函数返回时自动删除。
的
int fd2 = open("output", O_RDONLY, S_IWUSR | S_IRUSR);
if (fd2 < 0) {
printf("Error opening file\n");
return 1;
}
char bufferRead[sizeof(PointFull)];
read(fd2, bufferRead, sizeof(bufferRead));
//Now as you've read it, just cast the memory to struct, and assign it
item = *reinterpret_cast<PointFull*>(bufferRead);
//okay, now item holds the file content, you no longer need the buffer
另请注意:您的结构可能通过插入填充来对齐。虽然我不认为PointFull就是这种情况,但无论如何,当你需要序列化这里的结构时,你最好用#pragma pack
声明它不允许填充。 E.g:
#pragma pack(push, 1) // exact fit - no padding
struct PointFull {
double lat;
double lon;
};
#pragma pack(pop) //back to whatever the previous packing mode was
答案 2 :(得分:1)
您可以使用fwrite和fread将数据写入文件并从文件中读取 下面是相同的示例代码。
#include <stdio.h>
struct PointFull
{
int number;
char text[10];
double real_number;
};
int main()
{
struct PointFull data = {1, "Hello!", 3.14159}, read_data;
FILE *fout = fopen("file_path", "w");
fwrite(&data, sizeof(PointFull ), 1, fout);
// fprintf(fout, "%d %s %f",data.number, data.text, data.real_number);
fclose(fout);
FILE* fin = fopen("file_path", "r");
fread(&read_data, sizeof(PointFull ), 1, fin);
printf("%d %s %lf\n", read_data.number, read_data.text, read_data.real_number);
fclose(fin);
return 0;
}