如何读取二进制文件并保存到C中的数组?

时间:2022-07-01 11:08:25

I have a file in csv format look like this:

我有一个csv格式的文件如下:

0.0060862,0.31869
0.025889,0.21183
0.064364,0.094135
0.10712,-0.0081176
0.15062,-0.073904

I would like to load the first column to array a and second column to array b. This is what the code looks like:

我想将第一列加载到数组a中,第二列加载到数组b中,代码是这样的:

double a[5];
double b[5];
int i=0;
FILE* fileHandle = NULL;
fopen_s(&fileHandle, fileName.csv, "r+");
for(i=0;i<5;i++)
{
 fscanf_s(fileHandle,"%lf,%lf",a[i],b[i]);
}
fclose(fileHandle);

Now I am converting the csv file to a binary file; the data is represented in 2's complement in unsigned int. How should I change my code? I changed the code to

现在我将csv文件转换成二进制文件;数据在2的补码中以无符号整数表示。我应该如何更改代码?我把代码改为

unsigned x[5];
unsigned y[5];
double a[5];
double b[5];
int i=0;
FILE* fileHandle = NULL;
fopen_s(&fileHandle, fileName.csv, "rb+");
for(i=0;i<5;i++)
{
 fscanf_s(fileHandle,"%u,%u",x[i],y[i]);
 a[i] = x[i]/(2^15);
 b[i] = y[i]/(2^15);
}
fclose(fileHandle);

But x[i] and y[i] read from the binary is always 3435973836. How should I change my code to make it work?

但是x[i]和y[i]从二进制数中读取的总是3435973836。我该如何更改代码以使其生效?

1 个解决方案

#1


0  

When your data is binary, you don't need to convert it with fprintf and fscanf. You can just read and write you array with fread and fwrite.

当数据是二进制时,不需要使用fprintf和fscanf对其进行转换。你可以用fread和fwrite来读写数组。

If your data alternates a and b records, you will better organize your variables the same way :

如果您的数据交替使用a和b记录,您将更好地以相同的方式组织变量:

struct ab {
     int a, b;
     } ab[5];

and read it all in one shot with

把它全部读一遍。

fread(ab, sizeof (int), 10, fileHandle);

Then process it the way you like.

然后按你喜欢的方式处理。

(see man fread, and man fwrite for details)

(详见man fread, man fwrite)

#1


0  

When your data is binary, you don't need to convert it with fprintf and fscanf. You can just read and write you array with fread and fwrite.

当数据是二进制时,不需要使用fprintf和fscanf对其进行转换。你可以用fread和fwrite来读写数组。

If your data alternates a and b records, you will better organize your variables the same way :

如果您的数据交替使用a和b记录,您将更好地以相同的方式组织变量:

struct ab {
     int a, b;
     } ab[5];

and read it all in one shot with

把它全部读一遍。

fread(ab, sizeof (int), 10, fileHandle);

Then process it the way you like.

然后按你喜欢的方式处理。

(see man fread, and man fwrite for details)

(详见man fread, man fwrite)