gpt4 book ai didi

c - C 中的快速双文件读取

转载 作者:行者123 更新时间:2023-11-30 20:21:16 25 4
gpt4 key购买 nike

我有一个包含 float 的大文件,我想读取它们。

   52.881 49.779 21.641 37.230 23.417 7.506 120.190 1.240 79.167 82.397 126.502 47.377 112.583 124.590 103.339 5.821 24.566 38.916 42.576 

这只是文件的开头。它有 10000000 个号码。

我得到了这个代码,但我不知道如何打印这些数字。

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <fcntl.h>
#include <sysexits.h>
#include <unistd.h>

int main()
{
int fd;
size_t bytes_read, bytes_expected = 1000000*sizeof(double);
double *data;
char *infile = "file.dat";

if ((fd = open(infile,O_RDONLY)) < 0)
err(EX_NOINPUT, "%s", infile);

if ((data = malloc(bytes_expected)) == NULL)
err(EX_OSERR, "data malloc");

bytes_read = read(fd, data, bytes_expected);

if (bytes_read != bytes_expected)
err(EX_DATAERR, "Read only %d of %d bytes",
bytes_read, bytes_expected);

/* print all */

free(data);

exit(EX_OK);
}

最佳答案

您正在尝试读取文本文件,就像数据是二进制一样,因此您将读取一些字节,但存储在数组中的 double 值将不是您想要读取的值文件,你也许可以这样做

FILE *file;
double *array;
size_t count;
const char *infile = "file.dat";

file = fopen(infile, "r");
if (file == NULL)
return -1;
count = 0;
while (fscanf(file, "%*lf") == 1)
count += 1;
rewind(file);
array = malloc(count * sizeof(*array));
if (array == NULL) {
fprintf(stderr, "cannot allocate %zu bytes!\n", count * sizeof(*array));
fclose(file);
return -1;
}
// Read the values into the array
for (size_t i = 0; i < count; ++i) {
fscanf(file, "%lf", &array[i]);
}
// Print the array
for (size_t i = 0; i < count; ++i) {
fprintf(stdout, "%f\n", array[i]);
}
// Release memory
free(array);

关于c - C 中的快速双文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com