I tried to run the following program:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *datei = fopen("employees.txt", "w");
fprintf(datei, "Anna\n");
fclose(datei);
return 0;
}
Which should normally, if I understood correctly, generate the .txt file within the same folder of my C file, in case the file does not exist within the folder, or overwrite it if it does. However, no matter how many times I run the program, no file is being generated nor overwritten in case it exists.
I then thought that my *.c
file being saved within the cloud was the problem, so I saved it directly on my PC — same outcome.
I proceeded to inserting the absolute path:
FILE *datei = fopen("C:\\Users\\für\\JustCoding", "w");
fprintf(datei, "Anna\n");
Same outcome.
I restarted my PC (Windows 11 Home) and repeated above-mentioned steps; nothing.
Now I am pretty sure this has nothing to do with compilation errors, since my terminal does show me that the program was executed, so I am currently at a stand-still.
How do I solve this?
This code is correct and should create (or overwrite) a file named "employees.txt" in the current working directory of your program.
The issue you're facing is likely related to one of these factors:
To address these possibilities, let's modify your code to include error checking and print the current working directory:
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
int main() {
char cwd[1024];
if (_getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
FILE *datei = fopen("employees.txt", "w");
if (datei == NULL) {
perror("Error opening file");
return 1;
}
fprintf(datei, "Anna\n");
fclose(datei);
printf("File 'employees.txt' should have been created or overwritten.\n");
return 0;
}