fopen文本模式和ftell,fseek的跨平台问题探讨

本文探讨了在使用fopen以文本模式打开文件时,不应使用ftell和fseek的问题。由于这两个函数在二进制模式下工作更好,文本模式下在Windows和Linux等不同系统中可能产生不一致的结果。举例说明了一个简单的测试程序,该程序在读取文本文件时遇到的位置计算错误,强调了为避免此类问题应使用二进制模式进行读写操作。
摘要由CSDN通过智能技术生成

       当我们使用文本方式打开一个文本文件读取时,就不应该再使用ftell, fseek函数,因为这2个函数只适合于二进制模式 ,在文本模式下会因为系统的不同而产生不同的结果。

典型的文本方式打开比如:

     

FILE *fp = fopen("test.txt", "r");
FILE *fp2 = fopen("test2.txt", "rt");

        尝试在windows和linux编译并运行下面的测试程序,这个简单的程序就是从一个文本文件里,每次读取一个字符出来,并用ftell获取当前的位置:


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

int main()
{
	FILE *fp = fopen("test.txt", "rt");
	char buffer[2];
	int cur;
	for(int i = 0; i < 5; i++)
	{
		fgets(buffer, sizeof(buffer), fp);
		cur = ftell(fp);
		printf("read:%s cur:%d\n", buffer, cur);
	}
	fclose(fp);
	return 0;
}

           要处理的文本文件内容为:

hello_world

           请注意二进制格式为:

00000000h: 68 65 6C 6C 6F 5F 77 6F 72 6C 64 0A 0A          ; hello_world..


            Windows运行结果:

read:h cur:-1
read:e cur:0
read:l cur:1
read:l cur:2
read:o cur:3

             Linux运行结果:

read :h cur:1
read :e cur:2
read :l cur:3
read :l cur:4
read :o cur:5

               而且只有在文本换行符使用Linux方式时才会出现不一致,对于这个问题,微软的解释是:

When ftell() is used on a file opened in text mode that contains only linefeeds (0x0A) with no carriage returns (0x0D), ftell() may return an incorrect value on the first call, causing all subsequent return values to be wrong as well. Opening the file in binary mode eliminates this problem. A text file, by definition, contains CR-LF pairs that are condensed to single LF (linefeed) characters on input. A file that contains LF characters with no CR (carriage return) characters is an ill-formed text file and should be processed in binary mode.

            结论就是使用二进制方式读写才能保持一致了。

           



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值