首页 文章

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

提问于
浏览
1

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

这是我的课

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() ; 
    }
}

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

2 回答

  • 0

    问题是双向文件流都包含一个联合缓冲区,其中输入和输出都对要读取和写入的下一个字符产生影响 . 例如,在完成读取时,输出位置指示器也将增加读取的字符数 .

    modify 函数中,在执行 read 之后直接执行 write ,而不将输出位置指示器设置回0.这应始终完成以便接收预期结果 .

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

  • 3

    我正在Visual Studio 2010中进行编译,当我使用相同的代码并将其编译到其他ides(如代码块)时,它工作正常并输出预期的结果,我认为它是.Net问题或其他东西!

相关问题