如何读取和写入整数文件 [英] How to Read and Write integers to a file

查看:218
本文介绍了如何读取和写入整数文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的事情是,我尝试读一些整数知道我已经穿过了游戏的水平,那么我想提出一个目前水平的整数如果T尚未。它创建的文件,但不写什么。任何人都知道为什么吗?现在,它确实有它的printf创造它在第一时间,但读书时,它提供身份访问冲突。

 无效秘技(无效)
{
  FILE * PFILE =的fopen(SavedData.txt,RB);
  INT MYARRAY [8] = {0};  如果(PFILE)
  {
    的fscanf(PFILE,%D%D%D%D,MYARRAY [0],MYARRAY [1],MYARRAY [2],MYARRAY [3],MYARRAY [4],MYARRAY [ 5],MYARRAY [6],MYARRAY [7]);
    FCLOSE(PFILE);
  }  如果(MYARRAY [电流] == 0)
    MYARRAY [当前] = 1;  PFILE = FOPEN(SavedData.txt,世行);  如果(PFILE)
  {
    fprintf中(PFILE,%D%D%D%D,MYARRAY [0],MYARRAY [1],MYARRAY [2],MYARRAY [3],MYARRAY [4],MYARRAY [ 5],MYARRAY [6],MYARRAY [7]);
    FCLOSE(PFILE);
  }
}


解决方案

您可以做你想做的是这样的(未经测试):

 的#define SAVE_FILESavedData.txt
#定义NUMS_SIZE 8无效秘技(){
  FILE * F;  F = FOPEN(SAVE_FILE,R);
  如果(!F){
    fprintf中(标准错误,错误:无法打开保存读取档案\\ n);
    出口(-1);
  }  INT NUMS [NUMS_SIZE] = {0};
  INT N,I = 0;
  而(的fscanf(F,%D,&安培; N)== 1){
    如果(I> = NUM​​S_SIZE)打破;
    NUMS [我++] = N;
  }
  FCLOSE(F);  F =的fopen(SAVE_FILE,W);
  如果(!F){
    fprintf中(标准错误,错误:无法打开保存写入档案​​\\ n);
    出口(-1);
  }
  INT J = 0;
  如果(I 0)fprintf中(%d个,NUMS [0]);
  为(J = 1; J<我; ++ j)条
    fprintf中(%D,NUMS [J]);
  FCLOSE(F);
}

The thing is that im trying to read some integers to know the levels of the game I have already passed through, then I want to put the integer of the current level to one if t is not already. It creates the file but doesn't write anything. Anyone know why? Now, it does it the first time when creating it with printf but when reading it gives status access violation.

void SaveGame(void)
{
  FILE *pFile = fopen("SavedData.txt","rb");
  int MyArray[8] = {0};

  if(pFile)
  {
    fscanf(pFile, "%d %d %d %d %d %d %d %d" , MyArray[0], MyArray[1], MyArray[2], MyArray[3], MyArray[4], MyArray[5], MyArray[6], MyArray[7]);
    fclose(pFile);
  }

  if(MyArray[Current] == 0)
    MyArray[Current] = 1;

  pFile = fopen("SavedData.txt", "wb");

  if(pFile)
  {
    fprintf(pFile, "%d %d %d %d %d %d %d %d" , MyArray[0], MyArray[1], MyArray[2], MyArray[3], MyArray[4], MyArray[5], MyArray[6], MyArray[7]);
    fclose(pFile);
  }
}

解决方案

You can do what you want something like this (untested) :

#define SAVE_FILE "SavedData.txt"
#define NUMS_SIZE 8

void SaveGame() {
  FILE *f;

  f = fopen(SAVE_FILE, "r");
  if (!f) {
    fprintf(stderr, "Error: Can't open save file for reading.\n");
    exit(-1);
  }

  int nums[NUMS_SIZE] = {0};
  int n, i = 0;
  while (fscanf(f, "%d", &n) == 1) {
    if (i >= NUMS_SIZE) break;
    nums[i++] = n;
  }
  fclose(f);

  f = fopen(SAVE_FILE, "w");
  if (!f) {
    fprintf(stderr, "Error: Can't open save file for writing.\n");
    exit(-1);
  }
  int j = 0;
  if (i > 0) fprintf("%d", nums[0]);
  for (j = 1; j < i; ++j)
    fprintf(" %d", nums[j]);
  fclose(f);
}

这篇关于如何读取和写入整数文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆