简体   繁体   English

C:读取多个CSV文件

[英]C: Reading multiple CSV files

I need to read a CSV table and use its values for functions, but the scanf() function only reads the first column of the file. 我需要读取一个CSV表并将其值用于函数,但是scanf()函数仅读取文件的第一列。 I also need the code to be able to read more than one file, not allowing me to specify the name of the file. 我还需要能够读取多个文件的代码,而不允许我指定文件名。 What would be the correct way of doing so? 这样做的正确方法是什么?

Example: 例:

CSV file line: 114 -0.44 -0.15385 -0.76293 CSV档案行: 114 -0.44 -0.15385 -0.76293

Code output: 114 0.00 0.00 0.00 代码输出: 114 0.00 0.00 0.00

My code: 我的代码:

#include <stdio.h>
#include <tgmath.h>
#include <stdlib.h>

int main(){
    long sec;
    long wait = 0;
    int fall = 0;
    double x;
    double y;
    double z;
    double mag = 0.0;
    long i =0;

    while(1){
        scanf("%ld %lf %lf %lf", &sec, &x, &y, &z);
        mag = sqrt(pow(x,2)+pow(y,2)+pow(z,2));
        break;
    }

    printf("%ld %lf %lf %lf\n", sec, x, y, z);

    output1(wait);
    output2(fall);

    return 0;
}

If you are on Windows OS, you could use dirent.h and create an input directory, where you can store your input files. 如果您使用的是Windows操作系统,则可以使用dirent.h并创建一个输入目录,您可以在其中存储输入文件。

Once you have the files you can do a proper handling and start reading lines from it. 拥有文件后,就可以进行适当的处​​理并开始从中读取行。 Since you have a csv file, you can use the strtok to break the line into tokens and then load your variables with them. 由于您有一个csv文件,因此可以使用strtok将行拆分为标记,然后使用它们加载变量。

The thing stopping you from reading multiple files, is that you're using stdin to read the data rather than opening the files you want? 阻止您读取多个文件的原因是,您正在使用stdin读取数据,而不是打开所需的文件? If you're going to be doing the same thing repeatedly but with different input (ie filenames) you should create a function, something along the lines of... 如果要重复执行相同的操作,但使用不同的输入(即文件名),则应创建一个函数,类似...

void myfunc(char *filename)
  {
  FILE *thefile;
  double x,y,z;
  long sec;

  thefile=fopen(filename,"r");
  if(thefile)
    {
    if(fscanf(thefile,"%ld %lf %lf %lf", &sec, &x, &y, &z)==4)
      {
      /* do stuff */
      }
    fclose(thefile);
    }
  }

and then in your main you could use the command line arguments to specify the file names like so 然后在您的主目录中,可以使用命令行参数来指定文件名,如下所示

int main(int argc,char *argv[])
  {
  int i;
  for(i=1;i<argc;i++)
    {
    myfunc(argv[i]);
    }
  }

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

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