I need to write a program that asks the user to enter strings, each string ends when the user presses 'Enter'.
- The program needs to receive the file name as a parameter, the file should be opened and closed for each operation and for every string entered, the program should append the string to the end of the file (on a new line).
This is my code so far:
int is_file_exists(char *file_name) { FILE *file; if ((file = fopen(file_name,"r"))!=NULL) { /* file exists */ fclose(file); return 1; } else { //File not found, no memory leak since 'file' == NULL //fclose(file) would cause an error return 0; } } int main(int argc, char **argv) { char c; FILE *file; if (argc >= 2) { if (is_file_exists(argv[1])) { file = fopen(argv[1], "w"); } else { return 0; } } else { file = fopen("file.txt", "w"); } while ((c = getchar()) != EOF) { putc(c, file); } return 0; } So far the code compiles and file is being created, but nothing is being written inside of it.
Edit: I also need some function pointers, see my comments on selected answer
cneeds to be anintasEOFis anint. As it is, the loop will never end. Secondly, are you exiting the program and if so how? I ask because you do not close or flush the file. If you have not exited the program or if you force kill the program it may not correctly write the file.