【问题标题】:Writing Fixed length records into a file c++将固定长度记录写入文件c ++
【发布时间】:2016-09-01 17:49:31
【问题描述】:

我正在尝试写N个struct类型的固定长度记录

const int N = 101;
char dummay[] = "#####";

struct hashTable
{
   char  name[51];
   int RRN;
};
int main(){
    fstream f("hashFile.txt");
    f.seekp(0,ios::beg);
    hashTable h;
    for (int i = 0 ; i < N ; i++ ) {
       strcpy(h.name,dummay);
       h.RRN = i;
       f.write((char*)&h,sizeof h);
     }

当我再次尝试输出这些记录时,只有前 25 条记录运行良好!

f.seekp(0,ios::beg);
for (int i = 0 ; i < N ; i++ )
{
    f.read((char*)&h,sizeof h);
    cout << h.RRN << endl << h.name << endl;
}

完整的code,为什么会发生这种情况以及如何解决?!

【问题讨论】:

  • 使用正确的变量名
  • 您在ideone上显示的代码正确输出超过25条记录。
  • 我的电脑上只有 25 条记录正确,但是问题解决了,看第一个答案。

标签: c++ file fstream fixed-length-record


【解决方案1】:

您显然是在将二进制数据写入文件(int、名称中的空终止符和可能跟在名称后面的 45 个垃圾字符)。

所以用二进制模式打开就可以了:

fstream f("hashFile.txt", ios::binary); 

在文本模式下读取文件时,根据您的操作系统,一些二进制字符可能会被解释为文件结束标记。例如Ctrl+Z on windows(碰巧是ASCII码26)

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多