C ++.写入相对文件后,我无法显示内容 [英] C++. After writing into a relative file, I cannot display the content

查看:125
本文介绍了C ++.写入相对文件后,我无法显示内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以写入相对文件 1 ,然后当我尝试读取内容并将其显示在屏幕上(以检查数据是否确实存在文件中)时,我没有我认为文件中已经存在的记录.我正在使用Dev-C ++.任何帮助将不胜感激.代码如下;

I can write into a relative file1, then when I try to read the content and display it on the screen (to check if data are actually into the file), I do not have the records which I believe are already present in the file. I am using Dev-C++. Any help will be appreciated. The code is below;

#include <iostream>   //   cin, cout
#include <iomanip>
#include <fstream>
#include <conio.h>
using namespace std;


#define SIZE 10

struct     client        // Client record
{   
    int    account;      // from 1 to SIZE
    char   name[20];
    double balance;
};


void make_file(char filename[], int number_of_records)
{
  cout << "\nMAKE_FILE: Creating a blank relative file " << filename
     << " containing " << number_of_records << " records.";
  ofstream OS(filename, ios::out);
  if(!OS) {cerr << "File open error." << endl; exit(1);}

  client blank={0, "", 0.0}; // Create an empty client record
  while(number_of_records--)
  OS.write((char *)&blank, sizeof(blank));
  cout << "\nFile created.";
  OS.close();
}
int main(void)
{  
   client c;
   void *ptr; 
   int n=0;  
   char *fname = "credit.txt";
   make_file(fname, SIZE);

   fstream iof("credit.txt",ios::in | ios::out);
   if(!iof)
   {
       cerr<<"File open error! "<<endl;
       exit(1);
   }
   cout<<"\n\nenter the 10 customers into the file: "<< fname<<endl<<endl;

   while(0 < c.account) // && c.account <= maxrec)
   {
      iof.seekp((c.account-1) * sizeof(client));  // position the pointer
      iof.write((char *)&c, sizeof(c));
      cout << "Account[1.."<< SIZE
       << "], Name, Balance  (0 0 0 to exit)= ";
      cin >> c.account >> c.name >> c.balance;
   }

    cout << "\n\nSHOW_FILE: The contents of file " << fname;
    iof.seekg (0, ios::beg);  
    while(iof.read((char *)&c, sizeof(c)))  //where I think the problem is
    {
        cout <<'\n'<< setw(3)<< ++n << setw(6) << c.account <<setw(20)
       << c.name << setw(10) << c.balance ;
       // << "     |  " << IS.eof() << "  " << ptr;

    }
    iof.close();

    cout << "\n\n"; 
    system("pause");
    return 0;

}


  1. 相对文件是一种文件,其中的每个记录都可以通过其在文件中的顺序位置来标识,从而可以进行随机访问和顺序访问.

  1. A relative file is a file in which each record is identified by its ordinal position in the file allowing for random as well as sequential access.

相对文件

http://cayfer.bilkent.edu.tr/~cayfer/ctp108/relative.htm

推荐答案

您需要使用二进制读/写.

You need to use binary reading/writing.

fstream iof("credit.txt",ios::in | ios::out | ios::binary);

这篇关于C ++.写入相对文件后,我无法显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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