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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With