标准IO fgets的使用

因为工作的需要,需要按行读取文件内容。所以偷懒直接使用了fgets来使用。

使用过程中,发现fgets在读取行内容的过程中,会将末尾的换行符 '\n'也读进来。

测试代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>


int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	char buff[256];
	int ret = 0;
	int i = 0;
	
	if(argc != 2)
	{
		printf("param is error.\n");
		printf("please input: ./a.out file\n");
		return -1;
	}

	fp = fopen(argv[1], "r");
	if(fp == NULL)
	{
		printf("fopen %s fail.\n", argv[1]);
		return -1;
	}

	while(!feof(fp))
	{
		memset(buff, 0, sizeof(buff));
		if(fgets(buff, sizeof(buff), fp) != NULL)
		{
			//先打印出来读取到的内容
			for(i = 0; i < strlen(buff); i++)
			{
				printf("%.2x ", buff[i]);
			}

			printf("\n");
			
			//直接打印字符串
			printf("buff:%s", buff);			//注意,这里printf是没有加 '\n' 的
			//去掉最后的换行符
			buff[strlen(buff) - 1] = '\0';
			printf("buff:%s\n", buff);
		}		
	}

	return 0;
}

测试输入文件内容:

iiiiiiii

测试程序输出结果:

69 69 69 69 69 69 69 69 0a
buff:iiiiiiii
buff:iiiiiiii

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

monkey_llll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值