2017-03-01 51 views
-1

嗨,我正在处理两个txt文件。在第一个,我用fstream打开文件,但是当我试图用fstream打开第二个文件不起作用时,但是如果我尝试使用ofstream作品打开它。任何线索是怎么回事?下面是功能。由于Fstream doens't打开一个文件,ofstream是

void stack::read() 
{ 
    string name = "file.txt", line; 
    fstream file; 
    file.open(name.c_str());//open the file 
    char cc; 

    if (!file) 
    { 
     cout << "Error could not open the file" << endl; 
     return; 
    } 
    else 
    { 
     //file was opened succesful 
     while (file) 
     { 
      file.get(cc);//get each character of the string 
      push(cc);//insert the character into the stack 

     } 
    } 
    file.close();//close the file 
} 

void stack::write() 
{ 
    item *r = stackPtr;//point to the top element of the stack 
    ofstream file; 
    string name = "f.txt"; 
    file.open(name.c_str()); 

    if (!file) 
    { 
     cout << "Could not open the file" << endl; 
     return; 

    } 
    else 
    { 
     while (r != NULL)//while r has data write to the file 
     { 
      file << r->character; //write to the file 
      r = r->prev;//move to the prev element in the stack 
     } 
    } 
    file.close(); 
} 
+3

它存在吗? – SingerOfTheFall

+0

'ofstream'并不打算打开一个文件,而是创建一个新的文件,然后打开。 –

+0

始终使用适当的流类型来避免问题。所以当只读时,只使用'std :: ifstream',只写时使用'std :: ofstream'。 – zett42

回答

6

如果文件不存在,它可以与ofstream打开(它会创建同名的新文件)。但fstream.open()没有第二个参数假定读取模式,如果该文件不存在,它将不会被打开。

你确定你没有拼错文件名吗?

相关问题