c - 使用 fscanf() 跳转到下一行

标签 c file csv scanf

我有两个文件.csv,我需要读取整个文件,但它必须按字段归档。我的意思是,csv 文件是用逗号分隔数据的文件,所以我不能使用 fgets
我需要读取所有数据,但我不知道如何跳到下一行。

这是我到目前为止所做的:

int main()
{
   FILE *arq_file;
   arq_file = fopen("file.csv", "r");

   if(arq_file == NULL){
      printf("Not possible to read the file.");
      exit(0);
   }

   while( !feof(arq_file) ){
   fscanf(arq_file, "%i %lf", &myStruct[i+1].Field1, &myStruct[i+1].Field2);  
   }

   fclose(arq_file);
   return 0;
}  

它将进入无限循环,因为它永远不会得到下一行。
我怎样才能到达我刚刚阅读的那一行下面的那一行?

更新:文件 01 示例

1,Alan,123,
2,Alan Harper,321
3,Jose Rendeks,32132
4,Maria da graça,822282
5,Charlie Harper,9999999999  

文件 02 示例

1,320,123
2,444,321
3,250,123,321
3,3,250,373,451
2,126,621
1,120,320
2,453,1230
3,12345,0432,1830

最佳答案

我认为一个例子比给你提示更好,这是 fgets() + strtok() 的组合,还有其他功能可以工作,例如strchr(),尽管这种方式更容易,而且因为我只是想为您指明正确的方向,所以我是这样做的

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

int
main(void)
{
    FILE  *file;
    char   buffer[256];
    char  *pointer;
    size_t line;

    file = fopen("data.dat", "r");
    if (file == NULL)
     {
        perror("fopen()");
        return -1;
     }

    line = 0;
    while ((pointer = fgets(buffer, sizeof(buffer), file)) != NULL)
     {
        size_t field;
        char  *token;

        field = 0;
        while ((token = strtok(pointer, ",")) != NULL)
         {
            printf("line %zu, field %zu -> %s\n", line, field, token);

            field  += 1;
            pointer = NULL;
         }
        line += 1;
     }
    return 0;
}

我认为代码的工作原理已经很清楚了,希望您能理解。

关于c - 使用 fscanf() 跳转到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843205/

相关文章:

c - 如何从 C 中的 pthread 线程返回一个值?

C# 获取当前目录的真实路径

c - 从数组中检索多维数组

c - 我无法计算 0<= number <1 的平方

C、sendfile()和send()的区别?

java - 从 IOException 对象获取文件

java - 从列表中提取文件名

java - 使用 apache poi 将 .xls 转换为 csv 文件

R/Shiny - 如何响应式地编写包含 actionButton 的 .csv?

ruby-on-rails-3 - Rails CSV 将 ""而不是实际引号