Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a line from a text file in c/c++? [duplicate]

Tags:

c++

c

After exhaustive googling and visiting many forums, I am yet to find a good comprehensive answer for this question. A lot of the forums suggest using the get line istream& getline (char* s, streamsize n ) function. My question is what if I don't know what the length of each line is and cannot predict what the size may be? Also what is it's equivalent in C?

Is there any specific function in c /c++ to read one single line each time from a text file ?

Explanation , with Code snippets will help me a lot.

like image 450
Eternal Learner Avatar asked Jun 20 '10 23:06

Eternal Learner


People also ask

How do you read in a line from a file C?

The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be. You can find all the code examples and the input file at the GitHub repo for this article.

How do you read the contents of a file in C++?

File Handling in C++Create a stream object. Connect it to a file on disk. Read the file's contents into our stream object. Close the file.


1 Answers

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("filename.txt");
    std::string line;

    while( std::getline( input, line ) ) {
        std::cout<<line<<'\n';
    }

    return 0;
}

This program reads each line from a file and echos it to the console.

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

#include <stdio.h>

int main() {
    char line[1024];
    FILE *fp = fopen("filename.txt","r");

    //Checks if file is empty
    if( fp == NULL ) {                       
        return 1;
    }

    while( fgets(line,1024,fp) ) {
        printf("%s\n",line);
    }

    return 0;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

like image 110
Jacob Avatar answered Oct 12 '22 02:10

Jacob