Puzzle

关于feof()的bug??

这是我针对feof()错误有专门写的一个简单的测试.

1.写5条记录到文件，每条一个字串，一个整数。

2。从文件里读出，结果feof()无法识别。

    #include <iostream>
    #include <fstream>

    using namespace std;

    int main()
    {
    	char *str[5] = {"first","second", "third","fourth","fifty"};
    	int  index[5] = {0, 1, 2, 3, 4};

    	FILE* stream;

    	//write 5 record in file, each record is a string and int.
    	stream = fopen("c:\\nickfile.txt", "w+b");
    	for (int i=0; i<5; i++)
    	{
    		fwrite((void*)str[i], sizeof(char), strlen(str[i]), stream);
    		fputc('\0', stream);   //use null for end
    		fwrite((void*)(&index[i]), sizeof(int), 1, stream);
    	}

    	FILE* file;

    	fclose(stream);
    	char buffer[20], ch;
    	char* ptr = buffer;
    	int number;

    	file = fopen("c:\\nickfile.txt", "r+b");
    	while(!feof(file))   //this is not functioning well!!
    	{
    		ptr = buffer;
    		do
    		{
    			ch = fgetc(file);
    			*ptr = ch;
    			ptr++;
    		}
    		while (ch!='\0');
    		cout<<"str is:"<<buffer<<endl;
    		fread((void*)(&number), sizeof(int), 1, file);
    		cout<<"index is:"<<number<<endl;
    	}

    	return 0;
    }

    3。 我问了学校里c++的老师，她的意思这仿佛是一个人人皆知的bug.她说如果用fstream的类，就不会有问题，我就又写

    了一个测试。如下：

    4。数据之间用换行符隔开，这应该是ofstream的默认吧。结果，ifstream.eof()函数正常。

    #include <iostream>
    #include <fstream>

    using namespace std;

    int main()
    {
    	char *str[5] = {"first","second", "third","fourth","fifty"};
    	int  index[5] = {0, 1, 2, 3, 4};

    	ofstream out;
    	out.open("c:\\nickfile.txt");
    	for (int i=0; i< 5; i++)
    	{
    		out<<'\n'<<str[i];
    		out<<'\n'<<index[i];
    	}

    	out.close();

    	char buffer[20];
    	int number;
    	ifstream in;
    	in.open("c:\\nickfile.txt");
    	while (!in.eof())
    	{
    		in>>buffer;
    		cout<<"str is:"<<buffer<<endl;
    		in>>number;
    		cout<<"number is:"<<number<<endl;
    	}

    	return 0;
    }