函数读取csv文件,用空字符替换分隔符并计算列数和换行符,但返回错误的'\ n'数,我不明白为什么?请帮忙!
评论接近代码:应该是24643 - 实际24687
示例数据:我在必要时手动添加了','分隔符以显示列更改。
产品,23659,LAUX431GDS X431,图形诊断扫描工具,P,LAUX431GDS,CANDO INTERNATIONAL,对国内,欧洲和亚洲制造商的正确,OE级访问,读取/清除代码,实时数据绘图和双向记录定向测试和模块编码(4通道示波器,点火分析仪,传感器模拟器和万用表的单独模块将可用)
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;
}
答案 0 :(得分:1)
问题数量
主要问题是替换分隔符循环可能会将\n
替换为\0
。
次要:long fileSize
应为size_t fileSize
。
if (next != EOF){
应删除。
次要:buffer = malloc(fileSize + 1);
应为buffer = malloc(fileSize);
替换循环搞砸了
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';
}
}
}
代码未经测试 - 抱歉没有足够的时间。