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

标签 c file io

我有一个包含 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/

相关文章:

python - 'with open(file):'与手动打开/关闭它之间的性能差异

java.io.IOException : No space left on device Android 异常

python - 只要不输入空就打印数字

微 Controller 寄存器的更干净的命名空间

C 当返回 long 时,程序的行为就像我返回 int

javascript - 读取本地文本文件 - 字符集问题

c - 无休止的 while 循环和 fscanf 不将数据分配给结构

java - 使用 Visual Studio Code 进行 JUnit 测试时的路径问题

c++ - 如何在C套接字程序中接收HTTP GET和POST请求?

c - 使用c的文件中的行数