user1432532
user1432532

Reputation: 349

Why does my code only read the last line of the file?

I'm writing an application that will install some pre-compiled packages onto the ARM Chromebooks, and I didn't want to have to update my program every time I added a new package, so I set it up to just download a list of all the packages I have (which I can update) and then check that to see if it's a package I've compiled and uploaded to my site yet.

The problem is, it only seems to read the last line of the file. What confuses me the most is that it only reads the last line of this specific file. Most other files it reads all of the lines just fine.

Here's my code:

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <cstdio>
using namespace std;

int main(int argc, char* args[]) {
    if (argc < 2) {
        cout << "Please specify an application name.\n";
        return 0;   
    }
    cout << "Fetching list...\n";
    system("wget -N www.charmbrew.tk/files/list --quiet");

    cout << "Reading application list...\n";
    string line;
    string package = args[1];   
    bool isInList = false;  

    ifstream list("list");
    while (getline(list,line)) {
        cout << line;
        if (line == package) isInList = true;
    }
    list.close();
...
}

This code only reads the very last line of the file. The file contains three lines, but it only reads the last one. Every other file but this one on my PC it will read all of the lines.

I checked the file after it downloaded. I know it has multiple lines of text. But some reason my code keeps on only reading the last line.

The text file is just a simple text file. Nothing special about it. You can download it yourself and see.

Upvotes: 2

Views: 1199

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

The code reads every line, but the file list has CR LF as the line endings. This means every line read includes an \r at the end, which causes the next line written over the previous one.

If you want to see all lines, use

cout << line << '\n';

This is on a Unix system, where the line ending is a line feed only. On a Windows system, you have CR LF as line endings, there you should see all lines written on one line as

nanovimlynx

Upvotes: 6

Related Questions