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.