2015-11-05 55 views
0
上写的文件

我已经创建了一个函数来在文本文件上写入一些数据,并且它工作正常。我创建了另一个函数来读取文件的所有内容,并为我打印出来!但是,由于某种原因它不起作用。任何人都可以帮忙吗?我无法打印出我在

这是我的函数:

void myClass::displayFile() { 
    char line[LINE]; //to hold the current line 

    file.open("data.txt", ios::app); 

    //keep reading information from the file while the file is open and has data 
    while (!file.fail() && !file.eof()) { 
    int lineSize; //to loope through each line 

    file.getline(line, LINE); 
    lineSize = strlen(line); 

    //loop through the line to print it without delimiters 
    for (int i = 0; i < lineSize; ++i) { 
     if (line[i] == ';') { 
     cout << " || "; 
     } else { 
     cout << line[i]; 
     } 
    } 
    } 
    file.close(); 
    file.clear(); 

    if (file.fail()) { 
    cerr << "Something went wrong with the file!"; 
    } 
} 

注:该函数编译和循环是可访问的,但行字符串为空。

是写入功能:

void myClass::fileWriter() { 
    file.open("data.txt", ios::app); 
    file << name << ";" << age << ";" << "\n"; 
    file.close(); 
    file.clear(); 
} 
+1

我试过你的代码在我的一个文件上,我可以看到它打印的内容..你可以检查你的文件是否实际写入正确 – Megha

+1

为什么你打开追加模式,你没有写入文件?为什么你使用不同的尺寸来声明'line'和'getline'调用? ['std :: string'](http://en.cppreference.com/w/cpp/string/basic_string)和['std :: getline']有什么问题(http://en.cppreference.com/ w/cpp/string/basic_string/getline)(它们更安全并且不容易出现缓冲区溢出)?在循环之后检查'file.fail()',在检查之前你明确地清除标志是行不通的。 –

+0

哦,虽然[“为什么是”while(!feof(file))“总是错误的?”](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong )被标记为C编程语言,但C++和相同的问题存在'while(!file.eof())'。 –

回答

0

我傻,你的问题的原因是盯着我的脸,从一开始就和它的app开模这就是问题所在。它是在中打开文件模式,这意味着你无法读取它。

即使您可以从文件中读取,光标也会放置在文件末尾,eofbit标志本来会在第一次迭代中设置。

如果你想从一个文件中读取,然后要么使用std::ifstream自动设置in模式如果不指定模式,或者你要打开时明确设置in模式。

+0

是真的!在你告诉我它是写在一个文件上后,我试图删除它,然后我的代码工作得很好,我正准备在这里宣布它!但是,你明白了,谢谢 – Wilis1944