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;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值