Take a look at this code that allows a user to write data to a txt file.
#include <stdio.h>
int main(void)
{
FILE *cfPtr = NULL;
if ( (cfPtr = fopen("clients.txt","w")) == NULL ){
puts("File could not be opened");
}else{
puts("Enter the account, name, and balance");
puts("Enter EOF to end input.");
printf("%s", "? ");
int account = 0;
char name[30] = "";
double balance = 0.0;
scanf("%d%29s%lf",&account,name,&balance);
while (!feof(stdin)){
fprintf(cfPtr,"%d %s %.2f\n",account,name,balance);
printf("%s", "? ");
scanf("%d%29s%lf",&account,name,&balance);
}
fclose(cfPtr);
}
}
You can test it with
Enter the account, name, and balance
Enter EOF to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300 White 0.00
? 400 Stone -42.16
? 500 Rich 224.62
If I terminate the program with Ctrl+d, the program works fine and the above data is successfully written to the file. However, if I terminate it with Ctrl+c, nothing written in the txt
file. I'm wondering what is happening here. Why the program not at least writes the correct data immediately?
The compiler is gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
.
Pressing CTRL-D in a terminal doesn't terminate the program. It sends an EOF to the program (i.e. it closes the standard input stream) which the feof
function can detect.
Pressing CTRL-C however sends the SIGINT signal to the program. This signal, if not explicitly caught, will cause the program to terminate immediately.