C Traps and Pitfalls(1)

fread 和 fwrite 不能接连着使用,一般要在他们中间加fseek, 这是为了保持与之前程序的向下兼容性。spa

如如下程序,不管加不加fseek,都能编译而且执行经过,fread和fwrite都表示完成了任务。然而实际上,若是没有fseek这句话,fwrite并无将字符写入文件。code

 

#include <cstdio>
#include <cstdlib>
using namespace std;

int main()
{
	FILE *fp = fopen("test.txt", "r+");
	if (NULL == fp)
	{
		fprintf(stderr,"open file \"test.txt\" failed");
		exit(1);
	}
	char buf[256] = {0};
	size_t byteRead = fread(buf, sizeof(char), 10, fp);
	for (int i=0; i<byteRead; i++)
	{
		if (buf[i] > 'a' && buf[i] < 'z')
		{
			buf[i] = buf[i] + 'A' - 'a';
		}
	}
	//fseek(fp, -10, 1);
	size_t byteWrite = fwrite(buf, sizeof(char), byteRead, fp);
	if (byteRead != byteWrite)
	{
		fprintf(stderr, "read and write error");
		exit(1);
	}
	fclose(fp);
	return 0;
}
相关文章
相关标签/搜索