在CPP中读取.txt保存文件并将值保存到局部变量

时间:2014-10-29 15:17:29

标签: c++ save

我是C ++(和文件输入输出)的新手,我学习了如何使用fprint以格式化样式打印.txt中的内容,但是如何搜索某个值并将该值保存在本地变量?以下是保存代码:

 void savestate(state a){ //state is a struct with data I need such as position etc
    FILE * save;
    int data[]= { a.level, a.goalX, a.goalX, a.monX, a.monY }; 
    save = fopen("game.txt", "wb"); // << might have to use suggestion C 
    fwrite(data, sizeof(int), sizeof(data), save); // is this actually the correct way to do it?
    fclose(save);
 }

至于负载,我坚持这个:

void loadstate(){
    FILE* save;
    save = fopen("game.txt", "rb");
    if(save== NULL) perror("no savegame data");
    else{ 
         // don't even know what function I should use
    }

顺便说一句,在我激活保存功能后,game.txt的格式不是很可读。我可以在记事本中打开,但它显示的内容类似于毫无意义。任何的想法? :d

2 个答案:

答案 0 :(得分:1)

为此目的使用文本文件,而不是二进制文件。 saveData函数 将创建data.txt文件,然后函数loadData从文件中读取数据。我想要更多解释,请在下面发表评论。

#include <stdio.h>
#include <stdlib.h>

void saveData() {
    FILE* f = fopen("data.txt", "w");
    if(f == NULL) {
        printf("cant save data");
        return;
    }
    //write some data (as integer) to file
    fprintf(f, "%d %d %d\n", 12, 45, 33);
    fprintf(f, "%d %d %d\n", 1, 2, 3);
    fprintf(f, "%d %d %d\n", 9, 8, 7);

    fclose(f);
}

void loadData() {
    int data1, data2, data3;
    FILE* f = fopen("data.txt", "r");
    if(f == NULL) {
        printf("cant open file");
        return;
    }
    //load data from file, fscanf return the number of read data
    //so if we reach the end of file (EOF) it return 0 and we end
    while(fscanf(f, "%d %d %d", &data1, &data2, &data3) == 3) {
        printf("data1 = %d data2 = %d data3 = %d\n", data1, data2, data3);
    }

    fclose(f);

}

int main() {
    saveData();
    loadData();
    return 0;
}

答案 1 :(得分:-1)

写入文件的示例:

#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
int i = 78;
string word = "AWord";
ofstream fout("AFile", ios_base::out | ios_base::binary | ios_base::trunc);
fout << i;
fout << endl;
fout << word;
fout.close();

return 0
}

从文件中读取的示例:

#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main(){
int ix;
string wordx;
ifstream fin("AFile", ios_base::in | ios_base::binary);
fin >> ix;
while(fin.get() != '\n'){
   fin.get();
}
fin >> wordx;
fin.close();

return 0
}