C格式化读取txt文件内容

需求:

一个location.txt文件,内容如下:


格式化读取逗号分隔的的四个整数,存在一个结构体里


解决方法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

struct localtion{
	unsigned int lx;
	unsigned int ly;
	unsigned int rx;
	unsigned int ry;
	//char * textinfo;
};

int formatreadtxt(char *filename)
{
	FILE*fp;
	int num[10],j=0;
	char line[50];
	char ch;
	int line_num=1;
	struct localtion textarea={0};

	if ((fp=fopen(filename,"r"))==NULL)	{
		printf("读取文件失败!");
		return -1;
	}
	while(fgets(line,50,fp)!=NULL)
	{
		char temp[4]=" ";
		printf("第%d行:",line_num++);
		fputs(line,stdout);
		unsigned int label=0;
		for (int i=0;i<strlen(line);i++)
		{
			ch=line[i];
			if (isdigit(ch))
			{
				//将数字字符拼接,依次存入temp的前4个字符里
				temp[j++]=ch;
			}
			else if (ch==',')
			{
				j=0;
				label++;
				switch(label)
				{
					case 1:
						textarea.lx=atoi(temp);
						printf("lx:%d\n",textarea.lx);
						memset(temp, '\0', sizeof(temp));
						break;
					case 2:
						textarea.ly=atoi(temp);
						printf("ly:%d\n",textarea.ly);
						memset(temp, '\0', sizeof(temp));
						break;
					case 3:
						textarea.rx=atoi(temp);
						printf("rx:%d\n",textarea.rx);
						memset(temp, '\0', sizeof(temp));
						break;
					case 4:
						textarea.ry=atoi(temp);
						printf("ry:%d\n",textarea.ry);
						memset(temp, '\0', sizeof(temp));
						break;
					default:
						break;
				    }
			}
		}
        
	}
		

	//for (i=0;i<10;i++)
	//{
	//	fscanf(fp,"%d",&num[i]);//读入9个数据
	//}
	//for(i=0;i<10;i++)
	//{
	//	printf("%d ",num[i]);//显示9个数据
	//}
	
	fclose(fp);
	getchar();
	return 0;
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页