C语言从文件中读取多行用逗号分隔数据的解决方案
123456659,24666666,45461221,46465333, 123456659,24666666,45461221,46465333, 123456659,24666666,45461221,46465333, 例如数据如上,由于是用逗号分隔,所以要解决去掉逗号的问题。
第一种方法:用fgets函数从文件中读取数据,fgets读取数据时以回车或者EOF结束,读取一行后保存在数组中,然后判断是否为逗号,采取相应处理。
#include <stdio.h> #include <string.h> int main() { int i,j=0,k; FILE *fp=fopen("d://hh.txt","r"); if(fp==NULL) { printf("file open error/n"); return -1; } char buf[46]; char str[13]; memset(str,0,sizeof(str)); memset(buf,0,sizeof(buf)); while(!feof(fp)) { fgets(buf,sizeof(buf),fp); for(i=0;buf[i];i++) { if(buf[i]!=,) { str[j]=buf[i]; j++; } else if(buf[i]==,) { printf("%s/n",str); memset(str,0,sizeof(str)); j=0; } } memset(buf,0,sizeof(buf)); } fclose(fp); return 0; } 第二种方法:利用fscanf的格式可以用正则表达式来实现,思路简单
#include <stdio.h> int main() { FILE *fp=fopen("d://hh.txt","r"); if(fp==NULL) { printf("file open error/n"); return -1; } char str[11]; char ch; int i=0,count=0; fscanf(fp,"%[^,]%*c",str); printf("%10s/n",str); while(!feof(fp)) { fscanf(fp,"%[^,]%*c",str); printf("%10s/n",str); } fclose(fp); system("pause"); return 0; }
123456659,24666666,45461221,46465333, 123456659,24666666,45461221,46465333, 123456659,24666666,45461221,46465333, 例如数据如上,由于是用逗号分隔,所以要解决去掉逗号的问题。 第一种方法:用fgets函数从文件中读取数据,fgets读取数据时以回车或者EOF结束,读取一行后保存在数组中,然后判断是否为逗号,采取相应处理。 #include