fstream跳过第一个字符

fstream skips the first character

本文关键字:字符 第一个 fstream      更新时间:2023-10-16

我正试图将文本文件中的前121个字节读取到结构中。

这是我的密码。

#include <fstream.h>
#include <iostream.h>
#include <conio.h>
#include <sys/stat.h>
int main()
{
    struct 
    {
        char map[121];
    } map_data;
    struct stat results;
    fstream myfile("input.txt", ios::in);
    myfile.read((char *)&map_data,121);
    if(!myfile)
    {
           cout<<"Unable to open the file";
    }
    if(!myfile.read((char *)&map_data,121))
    {
       cout<<"Second error occurred";
    }
    myfile.close();
    cout<<"n Here are the read contents of size "<<sizeof(map_data)<<"n";

    fstream outfile("output.txt", ios::out);
    for(int i=0;i<121;i++)
    {
        cout<<map_data.map[i]<<" ";
    }
    outfile.write((char *)&map_data,121);

    outfile.close();
    stat("input.txt",&results);
    cout<<"n Size of input.txt "<<results.st_size;
    stat("output.txt",&results);
    cout<<"n Size of output.txt "<<results.st_size;
    getch();
}

问题是上面的代码跳过了文件的第一个字符,即hello的h。它的cout和output.txt文件都显示了这一点。

有人能指导我如何解决这个问题吗?

我遵循了指导课程。cs.vt.edu/cs2604/fall02/binio.html

该示例显示了读取文件的两种不同方法,注意一个中间示例。

它还说// Same effect as above

所以,只要评论掉两次阅读中的任何一次就可以了。

    fstream myfile("input.txt", ios::in);
    //myfile.read((char *)&map_data,121);
    if(!myfile.read((char *)&map_data,121))
    {
       cout<<"Second error occurred";
    }

我很惊讶只缺少第一个字符。它应该缺少121个字符。

fstream myfile("input.txt", ios::in);
// you read 121 bytes here...
myfile.read((char *)&map_data,121);
if (!myfile) {
    cout<<"Unable to open the file";
}
// and then do it again here, before you ever look at `map_data`.
if (!myfile.read((char *)&map_data,121)) {
    cout<<"Second error occurred";
}