2009-12-01 58 views
0

我正在写一个函数,它应该(如果文件已经存在)将第一个数字加1并将函数的参数追加到文件末尾。C++文本文件指针问题

实施例:

  1. 追加(4,9);
  2. append(5,6);

文件内容物在1: 1 \ N 4 \ n 9

文件内容物在2: 2 \ N 4 \ n 9 \ N 5 \ N 6

int append (int obj, int objType) { 

ifstream infile; 
infile.open("stuff.txt"); 

if (infile.fail()){ 
    infile.close(); 

    ofstream outfile; 
    outfile.open("stuff.txt"); 
    outfile << 1 << endl << obj << endl << objType; 
    outfile.close(); 
} 
else { 

    int length = 0; 

    while (!infile.eof()){ 
    int temp; 
    infile >> temp; 
    length ++; 
    } 

    infile.close(); 
    infile.open("stuff.txt"); 

    int fileContents[length]; 
    int i = 0; 

    while (!infile.eof()){ /*PROGRAM DOES NOT ENTER HERE*/ 
    infile >> fileContents[i]; 
    i ++; 
    } 

    infile.close(); 

    ofstream outfile; 
    outfile.open("stuff.txt"); 

    fileContents[0] +=1; 

    for (i = 0; i < length; i++){ 
    outfile << fileContents[i] << endl ; 
    } 

    outfile << obj << endl << objType; 


} 

的程序永远不会进入第二个while循环,所以内容永远不会复制到数组中,然后复制到文件中。我不确定问题是什么或如何解决。任何帮助将不胜感激。 :)

+1

您可能想要修复该格式。 – Catskul 2009-12-01 18:55:42

+0

...通过在每行加上4个空格。 – 2009-12-01 18:57:08

+1

谢谢:)新手在这里:) – Erica 2009-12-01 19:02:21

回答

2

,而不是关闭并重新打开文件这样(我不知道这是否操作的重置文件的位置,你需要!)为什么不使用std::fstream::seekg(),只是“倒带”文件开始

infile.seekg(0, ios::beg) 
+0

我已经尝试在int i = 0之后添加“infile.seekg(0,ios :: beg)”,但是while循环之后仍然被跳过(我假设因为某些原因,EOF标志仍然设置)。 谢谢你的时间。 :) – Erica 2009-12-01 19:36:51

+0

在调用seekg()之前调用'infile.clear()'。 – 2009-12-01 20:09:39

+0

它完美地工作。 :) 非常感谢! – Erica 2009-12-02 08:35:32

2

你还没有读取重置EOF标志,所以你仍然从前一个文件获得EOF。

这不是正确的文件输入方式。尝试更多的东西是这样的:

int temp; 
while (infile >> temp) 
{ 
    ... 
} 

而且看得出来,他在前面的问题联系尼尔·巴特沃思的博客文章:http://punchlet.wordpress.com/2009/12/01/hello-world/

+0

我明白,你的代码是更好的做法(mia culpa,感谢你指出),但我认为问题是第二次,而不是你所指的? 如何“[做]读取重置EOF标志”? 再次感谢。 :) – Erica 2009-12-01 19:33:05

+1

我指的是第二时间。 EOF标志只有在文件被读取,未打开或关闭时才被设置或清除。因此,在测试eof()之前,您需要先进行读取。在这种情况下,自上次循环中最后一次碰到EOF以来,您没有进行读取操作,因此eof()返回true,并且永远不会输入第二个循环。 – 2009-12-01 19:49:32

+0

但要阅读,我不需要将指针重置回文件的开头? – Erica 2009-12-01 20:04:46