There seem to be a LOT of ways you can get user input in C.
What is the easiest way that requires little code?
Basically I need to display this:
Enter a file name: apple.text
Basically I need to ask the user for a file name. So I need something that just gets that one word that the user will be inputting.
scanf
seems to work in a non-hostile environment. In other words, you're making a simple utility program for yourself.BUFSIZ usually far exceeds the size limits of UNIX pathnames.
If you need to accumulate data in a program that could be the target of buffer overrun, you might need a bit more.
The simplest "correct" way is probably this one, taken from Bjarne Stroustrup's paper Learning Standard C++ As A New Language.
(Note: I changed Bjarne's code to check for
isspace()
instead of just end of line. Also, due to @matejkramny's comment, to usewhile(1)
instead ofwhile(true)
...and so long as we're being heretical enough to edit Stroustrup's code, I've subbed in C89 comments instead of C++ style too. :-P)That covers:
Are there simpler but broken solutions, which might even run a bit faster? Absolutely!!
If you use scanf into a buffer with no limit on the read size, then your input exceeds the size of the buffer, it will create a security hole and/or crash.
Limiting the size of the reading to, say, only 100 unique characters of a filename might seem better than crashing. But it can be worse; for instance if the user meant
(...)/dir/foo/bar.txt
but you end up misinterpreting their input and overwriting a file calledbar.t
which perhaps they cared about.It's best to get into good habits early in dealing with these issues. My opinion is that if your requirements justify something close-to-the-metal and "C-like", it's well worth it to consider the jump to C++. It was designed to manage precisely these concerns--with techniques that are robust and extensible, yet still perform well.
Use this simple code
you should write your own fgets() wrapper function that reads a line of input into a buffer of a specified size and that removes the newline char that fgets() also reads. you could also return a status of whether or not the whole line was able to fit into the buffer (ie. is the newline at the end of the buffer). you shouldn't ever really use scanf or gets unless you want overflows.
EDIT: thought i might provide some basic code: