主题:fin.open打开文件后为什么是空的?
今天看了个小例子,但是不知道用fin.open 打开后,判断if (!fin)
{
cout << "Unable to open " << filename << "for reading.\n";
return(1);
}时fin是空,首先能确定的是要写入和写出的文件是存在的,而且前面也是可以读出和写入的,就是执行到fin.open出现了问题
[code=c]
请填写代码
// 17.17.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char filename[80];
char buffer[255];
cout << "Please re-enter the filename: ";
cin >> filename;
ifstream fin(filename);
if (fin)
{
cout << "Current file contents:\n";
char ch;
while (fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
}
fin.close();
cout << "\nOpening " << filename << " in append mode..\n";
ofstream fout(filename,ios::app);
if (!fout)
{
cout << "Unable to open " << filename << "for appending.\n";
return(1);
}
cout << "\nEnter text for the file: ";
cin.ignore(1,'\n');
cin.getline(buffer,255);
fout << buffer << "\n";
fout.close();
fin.open(filename,ios::in);
if (!fin)
{
cout << "Unable to open " << filename << "for reading.\n";
return(1);
}
cout << "\nHere's the contents of the file: \n";
char ch;
while(fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
fin.close();
return 0;
}
[/code]
{
cout << "Unable to open " << filename << "for reading.\n";
return(1);
}时fin是空,首先能确定的是要写入和写出的文件是存在的,而且前面也是可以读出和写入的,就是执行到fin.open出现了问题
[code=c]
请填写代码
// 17.17.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char filename[80];
char buffer[255];
cout << "Please re-enter the filename: ";
cin >> filename;
ifstream fin(filename);
if (fin)
{
cout << "Current file contents:\n";
char ch;
while (fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
}
fin.close();
cout << "\nOpening " << filename << " in append mode..\n";
ofstream fout(filename,ios::app);
if (!fout)
{
cout << "Unable to open " << filename << "for appending.\n";
return(1);
}
cout << "\nEnter text for the file: ";
cin.ignore(1,'\n');
cin.getline(buffer,255);
fout << buffer << "\n";
fout.close();
fin.open(filename,ios::in);
if (!fin)
{
cout << "Unable to open " << filename << "for reading.\n";
return(1);
}
cout << "\nHere's the contents of the file: \n";
char ch;
while(fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
fin.close();
return 0;
}
[/code]