简体   繁体   English

使用 seekg() 读取 C++ 中的文件时出现问题

[英]Problem in using seekg() to read file in C++

I am learning to read and write file in C++ and find a problem.我正在学习在C++中读写文件并发现问题。

My test.txt file contains 3 string in 3 lines:我的 test.txt 文件在 3 行中包含 3 个字符串:

abc
def
mnp

My problem is: I don't understand why I need to use f.seekg(2, ios::cur);我的问题是:我不明白为什么我需要使用f.seekg(2, ios::cur); instead of f.seekg(1, ios::cur);而不是f.seekg(1, ios::cur); I know how to use seekg() in c++ and I think that I just need to ignore 1 byte to get the next line by the getline() function.我知道如何在 c++ 中使用seekg() ,我认为我只需要忽略 1 个字节即可通过getline() function 获取下一行。

This is my code:这是我的代码:

ifstream f;
    f.open("D:\\test.txt", ios::in);
    string str1, str2, str3;
    f >> str1;
    f.seekg(2, ios::cur);
    getline(f, str2);
    getline(f, str3);
    cout << str1 << " " << str2 << " " << str3 << endl;

Reason for your trouble is explained for example here:例如,这里解释了您遇到麻烦的原因:
Why does std::getline() skip input after a formatted extraction? 为什么在格式化提取后 std::getline() 会跳过输入?

However about your actual question about seekg .但是,关于您关于seekg的实际问题。 You open the file in text mode.您以文本模式打开文件。 This means that when you read the file, line feeds are given to your C++ code as single characters, '\n' .这意味着当您读取文件时,C++ 代码会以单个字符'\n'形式提供换行符。 But on the disk they may be something else, and it seems you are running your code on Windows .但是在磁盘上它们可能是别的东西,而且您似乎正在Windows上运行您的代码。 There newline in a text file is typically two bytes, CR (ASCII code 13) and LF (ASCII code 10).文本文件中的换行符通常是两个字节,CR(ASCII 代码 13)和 LF(ASCII 代码 10)。 Reading or writing in text mode will perform this conversion between a single character in your C++ string vs two bytes in the file for you.以文本模式读取或写入将在 C++ 字符串中的单个字符与文件中的两个字节之间执行此转换。

seekg works on offsets and does not care about this, offsets are same whether you open the file in text or binary mode. seekg在偏移量上工作并且不关心这一点,无论您以文本模式还是二进制模式打开文件,偏移量都是相同的。 If you use seekg to skip new line, your code becomes platform-dependent, on Windows you need to skip 2 bytes as explained above, while in other platforms such as Unix you need to skip just single byte.如果您使用seekg跳过新行,您的代码将依赖于平台,在 Windows 上您需要跳过 2 个字节,如上所述,而在其他平台(例如 Unix)中您只需跳过单个字节。

So, do not use seekg for this purpose, see the linked question for better solutions.因此,请勿为此目的使用seekg ,请参阅链接问题以获得更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM