2017-01-01 66 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; 
}