scanf
and fgets
both can be used, but one will probably be easier for your application.
scanf
can be used, but check the return value.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void) {
char filename[20];
while(scanf("%19s", filename) == 1) {
printf("filename: %s\n", filename);
}
if(errno) return perror("filename"), EXIT_FAILURE;
return EXIT_SUCCESS;
}
Outputs,
12345678901234567890
filename: 1234567890123456789
filename: 0
fgets
gets the entire line without matching it to input.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void) {
char filename[20];
while(fgets(filename, sizeof filename, stdin)) {
printf("filename: %s\n", filename);
}
if(errno) return perror("filename"), EXIT_FAILURE;
return EXIT_SUCCESS;
}
Outputs,
12345678901234567890
filename: 1234567890123456789
filename: 0
[\n]
Usually, too-long filenames either truncate or complain, this is easy to see with fgets
, eg, How to discard the rest of a line in C.