2017-01-01 68 views
0

我正在尝试使程序知道程序已打开多少次。从.txt文件获得一个整数

为此,我做了一个函数来检查名为save.txt的文件是否存在,如果不是,创建一个并将int 1写入它。如果文件存在,该函数应该将其加1。

问题是,尽管我可以将int 1保存到文件中,但我无法在之后对文件进行更改。

这里是我的代码:

#include <stdio.h> 
#include <string> 
#include <fstream> 
#include <Windows.h> 
#include <sstream> 
#include <iostream> 

fstream savefile("save.txt", ios::in | ios::out); 
int counter; 
int fileNumber; 

void openFile() 
{ 
    if(!savefile) 
    { 
     cout << "File does not exist!\n"; 
     int counter = 1; 
     savefile.open("save.txt", ios::in | ios::out | ios::app); 
     savefile.clear(); 
     savefile << counter; 
     cout << "Int is " << counter << endl; 
     savefile.close(); 
    } 
    else 
    { 
     cout << "File does exist!\n"; 
     savefile.open("save.txt", ios::in | ios::out | ios::app); 
     savefile >> fileNumber; 
     savefile.clear(); 
     savefile << fileNumber +1; 
     savefile.close(); 
    } 
} 
+2

“_I我无法更改这一文件afterwards._”为什么发生了什么或有什么错误? –

+2

原谅我 - 你似乎缺少'主' –

+0

嗨,主要在那里。这个函数在main中被调用。 – TimberX

回答

0

这是我做的:

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::ifstream InFile; 
    std::ofstream OutFile; 
    int ExecutionCounter; 

    // try to read 
    InFile.open("SaveFile.txt"); 

    if (!InFile) 
    { 
     // file does not exsist - means first time 
     ExecutionCounter = 1; 
    } 
    else 
    { 
     // else, file exists, read the current and increment it 
     InFile >> ExecutionCounter; 
     ExecutionCounter++; 
     InFile.close(); 
    } 

    // .. 
    // your program tasks here 
    // .. 

    // on closing, save execution counter 
    std::remove("SaveFile.txt"); // remove old file 
    OutFile.open("SaveFile.txt"); // create new file 

    if (OutFile) 
    { 
     OutFile << ExecutionCounter; 
    } 
    OutFile.close(); 

    return 0; 
}