从csv文件中读取错误的'\ n'数

时间:2014-01-07 19:10:26

标签: c file-io fread

函数读取csv文件,用空字符替换分隔符并计算列数和换行符,但返回错误的'\ n'数,我不明白为什么?请帮忙!

评论接近代码:应该是24643 - 实际24687

示例数据:我在必要时手动添加了','分隔符以显示列更改。

产品,23659,LAUX431GDS X431,图形诊断扫描工具,P,LAUX431GDS,CANDO INTERNATIONAL,对国内,欧洲和亚洲制造商的正确,OE级访问,读取/清除代码,实时数据绘图和双向记录定向测试和模块编码(4通道示波器,点火分析仪,传感器模拟器和万用表的单独模块将可用)

  • 在所有车辆系统及其模块的诊断访问和通信中具有无与伦比的速度。启用Wifi,允许您访问自己喜欢的网站,以获取故障排除建议,图表和维修信息。
  • 一键更新,允许您一次更新一条或多条车线
  • 无需连接到PC进行更新,所有补丁和软件更新都直接通过您订阅每年都会更新该工具。
  • 包括更新的第一年

        int getCurrentData(FILE *current){
    
        int totalChars = 0, colCount = 0, productCount = 0;
        char *buffer = NULL, next = '\0';
        size_t i = 0;
    
        fseek(current, 0, SEEK_END);
        size_t fileSize = ftell(current);
        rewind(current);
    
        buffer = malloc(fileSize);
        fread(buffer, fileSize, 1, current);
    
        /*replacing delimiter with null character*/
        for (i = 0; i < fileSize; i++){
            if (buffer[i] == ',' && buffer[i+1] != ' '){
                buffer[i] = '\0';
            }
        }
        /*finds column and product count*/
        for (i = 0; i < fileSize; i++){
            if (buffer[i] == '\0' && productCount == 0 || buffer[i] == '\n' && productCount == 0){
                colCount++;
            }
            if (buffer[i] == '\n' && i < fileSize){
                productCount++;                         /*should be 24643 - actual 24687*/
            }
        }
    
        return productCount;
    }
    
  • 1 个答案:

    答案 0 :(得分:1)

    问题数量

    1. 主要问题是替换分隔符循环可能会将\n替换为\0

    2. 次要:long fileSize应为size_t fileSize

    3. if (next != EOF){应删除。

    4. 次要:buffer = malloc(fileSize + 1);应为buffer = malloc(fileSize);

    5. 替换循环搞砸了

      size_t fileSize = ftell(current);
      ...
      buffer = malloc(fileSize);           // later add error checking
      fread(buffer, fileSize, 1, current); // later add error checking
      /*replacing delimiter with null character*/
      for (size_t i = 0; i < fileSize; i++){
        if (buffer[i] == ',') {
          // Not sure why OP has (buffer[i+1] != ' ')?  Maybe \n was originally meant
          if ((i+1) >= filesize) || ((buffer[i+1] != ' ') && (buffer[i+1] != '\n'))) {
            buffer[i] = '\0';
          // Or rather than the above if(), maybe something simple:
          buffer[i] = '\0';
          }
        }
      }  
      
    6. 代码未经测试 - 抱歉没有足够的时间。