fstream跳过第一个字符
fstream skips the first character
我正试图将文本文件中的前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";
}
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 为什么第一个Dynamic_cast没有投射到基类?
- 将第一个n个字符复制到std :: string
- 一个奇怪的字符出现在我的字符数组的第一个
- 当一长串字符传递给第一个 cin 时,为什么不暂停第二个 cin 上的输入?
- 哪个字符是 c++ 中 4 个字符中的第一个
- 从 std::string 中提取(第一个)UTF-8 字符