C language reads .csv file data and group

C language reads .csv files and group them

The core is to use the',' comma to separate each group of data in the .csv file. We can use the strtok function of the C language to divide each row of data in the .csv file.

code show as below:

#include<bits/stdc++.h>
using namespace std;

void cut(char *line,int num)//读入这一行的数据 / 数据的组数-1(逗号的个数) 
{
    
    
	char *temp;
    temp=strtok(line,",");
    if(temp)
	{
    
    
   		printf("第1组数据:%6s\t",temp);//第一组数据 
	}
	for(int now=0;now<num-1;now++)
	{
    
    
		temp = strtok(NULL,",");
 		printf("第%d组数据:%6s\t",now+2,temp);//中间的数据 
  	}
  	temp = strtok(NULL,",");
  	temp[strlen(temp)-1]='\0';//把fgets读取的回车去掉 
 	printf("第%d组数据:%6s\n",num+1, temp);//最后一组数据 
}

int main(int argc, char *argv[])
{
    
    
    /*if(argc!=3)
    {
        return 0;
    }*/
    
    FILE *file = fopen("minute.csv","r");//读文件 
    if(!file)
    {
    
    
    	printf("file error");
    	return 0;
	}
	
	char line[1024];
	int num=0;
	fgets(line,1024,file);
	
	for(int now=0;line[now]!='\n';now++)//通过统计分割的逗号 来统计数据的组数 
	{
    
    
		if(line[now]==',')
		{
    
    
			num++;
		}
	}
	
	printf("一共有%d组数据\n",num+1);//有num个逗号 就是有num+1组数据 
	cut(line,num);//分割输出第一行 
	
    while(fgets(line,1024,file)!=NULL)//对之后行进行分割 
    {
    
    
    	cut(line,num);
	}
	
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45698148/article/details/108542864