C Traps and Pitfalls(1)

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

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

 

#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;
}

你可能感兴趣的:(c,Pitfalls,and,traps)