I would like to have the equivalent (in C) of getline in C++:
std::string s;
getline(std::cin,s); // reads an arbitrarily long line and
// inserts its contents on s
Is there any way to do such a thing in C? I’m looking for something that looks like this:
char* s;
getline(stdin,s); // allocates the space necessary to fit the read
// line and make s point to it
EDIT: I decided to use the POSIX getline function at the end since I’m on Linux (run man getline if you don’t know what I’m talking about), but Michael Burr provided an implementation of getline which works on other operational systems in which getline is not available by default. Even if his implementation is not the most efficient one could conceive, it does the job as I want so I marked it as the answer for my question.
In case you don’t have access to a POSIX
getline()implementation, here’s a public domain implementation that I have lying around.I added a little
getline_simple()function that just returns the next line in a dynamically allocated buffer. If you’re not interested in detailed error handling, you can use that function to read a file line-by-line:Disclaimer – this code has worked well enough for my purposes, but I don’t warrant that will be the case for you. Please use due diligence if intending to use this code.