1

Using std::fstream, after calling the testFile.getline() function, I call testFile.seekg(1, std::ios_base::cur); which its job is to advance the input position by 1, as it will do in every other scenario, but this time it simply does nothing and does not advance the input position. As shown in the code below:

std::fstream testFile;
testFile.open("test.txt", std::ios_base::in | std::ios_base::out | std::ios_base::trunc);
if (testFile.is_open())
{
    testFile.flush();
    testFile.seekp(0);
    char msg[]{ "GETTING IT TO WORK;\nNEXT LINE;\n" };
    testFile.write(msg, 32);
    testFile.put('\0');
    testFile.flush();
         
    std::string header;
    header.reserve(100);
    testFile.seekg(0);
    testFile.getline(&header[0], 100, ';');
    header.clear();

    //testFile.seekg(1, std::ios_base::cur); 
    //uncommenting this code will do nothing only if getline has not been called 
    //immediately before it, will do the advancing
    testFile.getline(&header[0], 100, ';');
}

Calling testFile.seekg(2, std::ios_base::cur) will advance the input position by 1 in this scenario only, but 2 when there's no getline() call before it.

I have read the documentation and test every scenario myself, but this behavior is not explained anywhere in docs, nor is it an expected behavior by the programmer.

Using MSVC v143 and ISO C++20.

1 Answer 1

2

The salient facts appear to be:

  • advancing it by one seems to make no difference;
  • advancing it by two looks like it advances it by one; and
  • this is immediately following a getline() and it's doesn't cause a problem otherwise.

That seems to indicate you may have a CR/LF file where the actual line endings are \r\n rather than \n. I'd check the content of the file with a hex dump utility to see if this is the case.

It's possible seek is actually working on binary content rather than text content so that skipping one character only skips the \r. If that is the case, then you can probably fix it by reading a character into a junk buffer rather than trying to seek ahead one byte. The former should hopefully handle line endings correctly. In other words, change:

testFile.seekg(1, std::ios_base::cur);

into:

int junk = testFile.get();

And, in fact, that appears to be what's happening. Consider the following program which does roughly the same as your code, but seeks to each position in turn and reads the line, printing the first character it read:

#include <iostream>
#include <fstream>

int main()
{
    std::fstream testFile;
    testFile.open("test.txt",
        std::ios_base::in | std::ios_base::out | std::ios_base::trunc);
    if (testFile.is_open())
    {
        char msg[] = "a\nb\nc;";
        testFile.write(msg, sizeof(msg));
        testFile.flush();

        char buff[10];
        for (int i = 0; i < 7; ++i) {
            testFile.seekg(i);
            testFile.getline(buff, 100, ';');
            std::cout << "<" << int(buff[0]) << " "
                      << ((buff[0] >= ' ') ? buff[0] : '.')
                      << "> <"
                      << int(buff[1]) << " "
                      << ((buff[1] >= ' ') ? buff[1] : '.')
                      << ">\n";
        }
    }
}

The output of that is:

<97 a> <10 .>
<10 .> <98 b>   *1
<10 .> <98 b>   *2
<98 b> <10 .>
<10 .> <99 c>   *1
<10 .> <99 c>   *2
<99 c> <0 .>

You can see that, when you seek to either the \r or the \n, the result of a character read is \n (decimal; 10 is line feed). I've marked the lines where that happens with *1 and *2.

So it appears the underlying I/O routines for text files will do something like the following:

  • if the next two characters are \r\n, you'll get a \n (*1).
  • if the next character is \n, you'll get a \n (*2).

That's why it appears to not seek ahead by one when the next character is the \r. It is seeking but the behaviour is as described above (seeking to the \n then acting as per *2).


A good debugging option, by the way, would have been to output testFile.tellg() after each file operation just to see where it thinks it is.

Interestingly, when I do that (under Linux), the buffer appears to move okay but the string prints as empty. If I replace string header with char header[200] (and make other adjustments to match), it seems okay. Note that the seek ahead by one works here, probably because it's a newline-ending platform.

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    std::fstream testFile;
    testFile.open("test.txt", std::ios_base::in | std::ios_base::out | std::ios_base::trunc);
    if (testFile.is_open()) {
        cout << testFile.tellg() << " a\n";

        testFile.flush();
        cout << testFile.tellg() << " b\n";

        testFile.seekp(0);
        cout << testFile.tellg() << " c\n";

        char msg[]{ "GETTING IT TO WORK;\nNEXT LINE;\n" };

        testFile.write(msg, 32);
        cout << testFile.tellg() << " d\n";

        testFile.put('\0');
        cout << testFile.tellg() << " e\n";

        testFile.flush();
        cout << testFile.tellg() << " f\n";

        char header[200];
        testFile.seekg(0);
        cout << testFile.tellg() << " g\n";

        testFile.getline(&header[0], 100, ';');
        cout << testFile.tellg() << " h\n";

        cout << '<' << header << ">\n";

        testFile.seekg(1, std::ios_base::cur);
        testFile.getline(&header[0], 100, ';');
        cout << testFile.tellg() << " i\n";

        cout << '<' << header << ">\n";
    }
}

This outputs:

0 a
0 b
0 c
32 d
33 e
33 f
0 g
19 h
<GETTING IT TO WORK>
30 i
<NEXT LINE>

I'd suggest trying that code on your platform to see what it outputs.


The reason why the direct writing to string didn't work appears to be that reserve() does not necessarily make things ready for that. I had to actually populate the string to be at least big enough (size, not just reserve capacity) so the direct write worked. And of course, I had to adjust the length afterwards because it's quite valid for C++ strings to hold \0 characters.

That's probably because the direct write simply places data into the string area but does not affect any other important properties of the string object (such as the length).

Refactoring the line reader out to this:

void getUpTo(fstream &strm, string &str, size_t sz, char delim) {
    if (str.length() < sz + 1)
        str.resize(sz + 1);
    strm.getline(&str[0], sz, delim);
    str.resize(str.find('\0'));
}

and changing the calls:

// from: testFile.getline(&header[0], 100, ';');
// to:
getUpTo(testFile, header, 100, ';');

made it work.

That's not immediately applicable to your line ending issue but you should keep it in mind if you appear to get empty/bad strings even when you fix that.

10
  • its a text format ansi encoded in notepad++ setting, and as with the CR+LF you're right it notepad++ says CR+LF, but what should I do?
    – Leon
    May 22 at 22:07
  • @Leon: "you can probably fix it by reading a character into a junk buffer rather than trying to seek ahead one byte" :-) Having said that, I'm not sure this is the problem, since you're using ; as the delimiter, not the default newline.
    – paxdiablo
    May 22 at 22:11
  • 1
    @Leon you are writing a string with \n in it to an fstream operating in text mode, so on Windows it will write \r\n to the actual file. And when reading and seeking, it will treat \r\n as a single character \n. If you don't want this behavior, put the fstream into binary mode instead, then it will treat each byte individually. May 22 at 23:54
  • 1
    @Remy, based on the description, it appears seeking up by one when you're on the \r\n is not treating it as a single character. I would actually expect it to given the file is in text mode.
    – paxdiablo
    May 23 at 8:32
  • 1
    @paxdiablo makes sense, since seeking doesn't read bytes (it would be really inefficient if it did) May 23 at 14:45

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.