c - 如何读取c中特定列的行?

标签 c file csv stream fgets

在检查该列是否为“常规”后,我尝试了多种方法来读取新行,但仍然不起作用。这是一个 csv 文件,每个 fgets 后面都会有逗号,我需要一个包含其数据的特定列。

这是我的代码:

char fi[1024];
while(!feof(CsvFile)){
    //Read
    fgets(fi, 1024, CsvFile);
    if(strstr(fi, "General") == 0){
        fscanf(CsvFile, "%[^\n]s", fi);
        printf("%s", fi);
    }
    fgetc(CsvFile);
}

它不打印我想要的内容。

最佳答案

读取 CSV 文件比您想象的要复杂得多(请参阅 https://www.rfc-editor.org/rfc/rfc4180)。您必须考虑所有类型的规则。例如,如果单元格包含逗号,则内容必须用 " 包围。

但是,您可以实现一个简化版本,它假设:

  • CSV 文件由行组成;
  • 一行最多 MAX_LINE 个字符;
  • 线由细胞组成;
  • 单元格以逗号或换行符结尾;
  • 单元格包含除逗号或换行符之外的任何内容。

下面的代码一次读取一行,然后使用 strtok将行拆分为单元格。

欢迎来到 SO,祝你好运!

#include <stdio.h>
#include <string.h>

#define MAX_LINE 1024

int main( int argc, char* argv[] )
{
  //
  FILE* fp = fopen( "c:\\temp\\so.txt", "r" );
  if ( !fp )
  {
    printf( "could not open file" );
    return -1;
  }

  //
  char line[ MAX_LINE + 1 ];
  while ( fgets( line, sizeof( line ) / sizeof( *line ), fp ) ) // get a line
  {
    int col_idx = 0;
    const char* sep = "\r\n,"; // cells are separated by a comma or a new line
    char* cell = strtok( line, sep ); // find first cell
    while ( cell )
    {
      // your processing code goes here
      cell = strtok( NULL, sep ); // next cell
      col_idx++;
    }
  }

  return 0;
}

关于c - 如何读取c中特定列的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210324/

相关文章:

使用 AVX 内在函数压缩掩码

c - 使用switch语句调用函数不起作用

.net - 自动从 .csv 下载并填充 SQL Server 表

python - 如何在python中检查上传的文件是csv还是xls?

c++ - 将文本文件附加到 char 数组,接收垃圾输出

python - 将包含一些标量和一些数组值的字典写入 csv

c - 在 C 中是否有更好的方法求函数的 n 阶导数?

c++ - fseeko, fseeko64; ftello、ftello64 Visual C 等效项

python - Python 和 Matlab 之间的共享文件访问

java - Eclipse - 在多个文件之间跳转的一般用法