简体   繁体   English

从C中的文本文件读取大量数字

[英]Reading large amounts of number from a text file in C

I am trying to read a large amount of numerical data (doubles) from a text file. 我正在尝试从文本文件中读取大量数字数据(双精度)。 The text file has 10 columns, each with 242 numbers listed in it. 文本文件有10列,每列列出了242个数字。 The columns are separated by spaces. 列由空格分隔。 I am trying to specifically take the first and seventh columns and put them into an array. 我正在尝试专门采用第一列和第七列并将它们放入数组中。 Currently I am trying this: 目前,我正在尝试:

int i;
double a;
double b;
double junk;
double array[2][242]

FILE *fp;
fp = fopen("data_table.dat", "w");
for (i = 0; i <= 242; i++);
{
    fscanf(fp, "%f %f %f %f %f %f %f %f %f %f\n", a, junk, junk, junk, junk, junk, b,
    junk, junk, junk);
    array[0][i] = a;
    array[1][i] = b;
}
fclose(fp);

The thought I had was to open the text file, read one row of the doubles and save the first column and seventh column then to the array, with the rest of them being junk. 我当时的想法是打开文本文件,读取双打的一行,然后将第一列和第七列保存到数组中,其余则为垃圾。 However when I examine the array afterwards every single entry in the array is 6.943e-310, which is not even close to any of the data that is in my data table. 但是,当我随后检查数组时,数组中的每个条目都是6.943e-310,它甚至与数据表中的任何数据都不接近。

Another thing that might be worth noting is that after I run this the entire text file is empty. 可能需要注意的另一件事是,运行此命令后,整个文本文件为空。 I can fill it again with values but then after I run the code it is empty again. 我可以再次用值填充它,但是在运行代码后,它再次为空。 Also the first entry in each column is a string of what the data in the column is (for example the first column starts of with length in nm). 此外,每列中的第一项也是该列中数据的字符串(例如,第一列以nm长度开始)。

You opened the file for writing with the "w" option in fp = fopen("data_table.dat", "w"); 您在fp = fopen("data_table.dat", "w");使用“ w”选项打开了要写入的文件fp = fopen("data_table.dat", "w");

You want to open it for reading instead with "r" otherwise it truncates the file, which is why you see nothing in it afterwards. 您想用“ r”打开它进行读取,否则将截断该文件,这就是为什么之后看不到它的原因。

  1. (as @Ranic has posted simultaneously) You want to read from "data_table.dat", but open it with "w". (因为@Ranic同时发布了)您想从“ data_table.dat”中读取内容,但是用“ w”打开它。 That call truncates the file to size 0. Use "r" instead. 该调用将文件截断为0号。改用“ r”。
  2. You have to pass pointers ( &junk , &a , &b ) to fscanf() instead of values 您必须将指针( &junk&a &b )传递给fscanf()而不是值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM