【问题标题】:Read specific line from .csv file in C从 C 中的 .csv 文件中读取特定行
【发布时间】:2017-05-27 14:17:06
【问题描述】:

我有一个这样的 CSV 文件(.csv 扩展名):

"id_product","name","brand","category","price"
0157,Sparachiodi,Mannesmann,FaiDaTe,32.99
0211,Cavi di rame,Chapuis,FaiDaTe,20.23
4815,Tenaglia,Ks Tools,FaiDaTe,7.50
8451,Lucchetto,Blinky,FaiDaTe,4.55

我的问题是:如何编写一些仅从第二行读取文件的 C 代码?我想做的是对文件进行某种研究。 (例如我想搜索名称为“cavi”的产品,我会显示整行。)

【问题讨论】:

  • “我怎样才能只从文件中读取第二行” - 在文本编辑器中打开文件并读取第二行?
  • 通过阅读并忽略第一行?你确实知道如何读一行,不是吗?
  • 是的,在文本编辑器中很容易,但在 c 中我如何只扫描一个特定的行?
  • 使用fgets。您无法从文本文件中读取特定行,您必须按顺序读取它们
  • 我们既不是咨询,也不是辅导或编码服务。你问的是每本 C 书中的标准课程。我建议您阅读一本或询问您的老师。

标签: c csv parsing


【解决方案1】:

您有一个 csv 文件。您知道合法的行很短(

所以

 char buff[1024];
 fgets(buff, 1024, fp); /* read line 1 */
 fgets(buff, 1024, fp); /* read line 2, overwriting line 1 */

但可能你想要的是这个

 char buff[1024];
 fgets(buff, 1024, fp);
 /* check buff is a legitimate csv header here */

 /* after we've got rid of the reader, do data lines until they run out */
 while(gets(buff, 1024, fp))
 {
    char *field = strtok(buff, ',');
    if(field)
    {
        /* numerical field, product id */
    }
    field = strtok(0, ',');
    if(field)
    {
         /* product name field */
    } 
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多