Look here, those two programms should be equivalent in my opinion. But obviously they aren't, as the first programm works and the second doesn't. Can someone explain to me, why fgets() doesn't do the job?
// FIRST PROGRAM : WORKS FINE #include <stdio.h> #include <stdlib.h> int main() { FILE *stream; char fileName[67]; scanf("%s", fileName); printf("%s", fileName); stream = fopen(fileName, "r"); char ch; if(stream){ ch = fgetc(stream); while(!feof(stream)){ putchar(ch); ch = fgetc(stream); } fclose(stream); } } // SECOND PROGRAM: DOES NOT WORK #include <stdio.h> #include <stdlib.h> int main() { FILE *stream; char fileName[67]; fgets(fileName, 67, stdin); printf("%s", fileName); stream = fopen(fileName, "r"); char ch; if(stream){ ch = fgetc(stream); while(!feof(stream)){ putchar(ch); ch = fgetc(stream); } fclose(stream); } } I enter "test.txt" into the console both times and press enter then. Of course test.txt exists in the right directory
fgets()retains thenewlineentered, please remove it.printf("[%s]", dateiname);then you can see thenewlineis there.