如果没有 seekg 和 seekp,c++ fstream write 不适用于二进制文件

标签 c++ file fstream

我需要按顺序读取和写入同一个文件(没有 seekg 和 seekp) 但出于某种原因 .write 不起作用!

这是我的类(class)

class student
{
    int id ; 
    char name[20]  ;
    int m1 , m2 , m3 ; 
public:
    student()
    {
    }
    student(int idd , char*n , int mm1 , int mm2 , int mm3 )
    {
        id = idd ; 
        strcpy(name , n); 
        m1 = mm1 ; 
        m2 = mm2 ; 
        m3 = mm3 ; 
    }
    void show()
    {
        cout<<"student id : "<<id<<endl<<"student name : "<<name<<endl<<"mark 1 : "<<m1<<endl<<"mrak 2 : "<<m2<<endl<<"mark 3 : "<<m3<<endl ;
    }
    void get()
    {
        cout<<"enter student id : " ; 
        cin>>id ; 
        cout<<"enter student name : " ; 
        cin.ignore() ; 
        cin.get(name , 20) ; 
        cout<<"enter student's mark 1 :" ; 
        cin>>m1 ; 
        cout<<"enter student's mark 2 :" ; 
        cin>>m2 ; 
        cout<<"enter student's mark 3 :" ; 
        cin>>m3 ; 


    }


};

这是我的主要功能:

   int main()
{
       fstream file("f://records.dat" , ios::out | ios::in  |ios::binary ) ; 
    if(!file)
    {
        cout<<"Error !";
        int z ; 
        cin>>z ;
        return 4 ; 

    }


    modify(file);

    int x ; 
    cin>>x ; 
    return 0 ; 
}

这是我的功能:

void modify(fstream &file)
{   
    int recnum  ;
    cout<<"enter the number of the record to be modified : " ; 
    cin>>recnum ;
    file.seekg(0) ; 
    file.seekp(0);
    student s1 ;
    for(int i = 0 ; i<recnum-1 ; i++) 
    {
        file.read((char *) &s1 , sizeof(s1)) ;  
    }
int x = file.tellp() ;
    int y = file.tellg() ; 
    cout<<x<<endl<<y<<endl ;   
student s2 ;
s2.get() ; 
    file.write((char *) &s2 , sizeof(student))
    x = file.tellp() ;
    y = file.tellg() ;
    cout<<x<<endl<<y<<endl ;   

    file.flush() ; 
        file.seekg(0 , ios::beg);
    if(file.eof())
    {
        cout<<"error !" ; 
        int x ; 
        cin>>x ; 
    }

        while(file.read((char *) &s1 , sizeof(student)))
    {
        s1.show() ; 
    }
}

似乎方法修改中的写入函数不起作用所以请任何人帮助我?????

最佳答案

问题是双向文件流都持有一个 union 缓冲区,其中输入和输出都对下一个要读取的字符产生影响写入。例如,当读取完成时,输出 位置指示器也会随着读取的字符数增加。

在您的modify 函数中,您在执行read 之后直接执行write,而没有将输出位置指示器设置回0。这应该总是为了收到预期的结果而完成。

输出后输入也是如此:不要忘记设置 seekg 位置指示器。

关于如果没有 seekg 和 seekp,c++ fstream write 不适用于二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872187/

相关文章:

c++ - 什么是线程间操作

c++ - 无法链接 ".o"目标文件

java - Android 丢失应用程序数据 (/data/data/com.app.app/files)

C++ fstream - 无法使用二进制格式从文件中读取

c++ - 读取矩阵中可变大小的列

c++ - 以编程方式退出 MFC 应用程序的正确方法是什么?

c# - 在数据迁移中传输大数据

eclipse - Eclipse中JSP文件的字符集、编码仍然是ISO-8859-1?

java - 使用 FileUtils.listfiles 读取子目录时出现问题

c++ - 使用 C++ 修复 .txt 文件中的列宽