读取.CSV文件并将其存储在另一个文件中

时间:2015-05-15 14:30:03

标签: c csv

制作了一个读取.csv文件的程序,并将最高编号存储在另一个文件中。问题是我的程序无法读取逗号分隔数字,如1,5,6,7,1,2。这是我需要帮助改变的循环

int i;
int max = 0;
int min = 0;
while (!feof(fp))
{
    fscanf( fp, "%d", &i);
    if (i < min)
    min = i;
    if (i > max)
    max = i;
}  

这就是我打印的内容:

    fprintf(q,"%d",max);
    printf("maximum value is %d \n", max);
    fclose(q);
    fclose(fp);

1 个答案:

答案 0 :(得分:1)

#include <stdio.h>
#include <limits.h>

int main(void){
    FILE *fp = fopen("input.csv", "r");
    FILE *q  = fopen("max.txt" , "w");

    int i;
    int max = INT_MIN;
    int min = INT_MAX;

    while(1){
        int state = fscanf(fp, "%d", &i);
        if(state == 1){
            if (i < min)
                min = i;
            if (i > max)
                max = i;
        } else if(state == EOF){
            break;
        } else {
            char ch;
            fscanf(fp, " %c", &ch);
            if(ch != ','){
                fprintf(stderr, "\nformat error\n");
                break;
            }
        }
    }

    fprintf(q, "%d", max);
    printf("maximum value is %d\n", max);
    fclose(q);
    fclose(fp);

    return 0;
}