Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between terminating a program with Ctrl+d and Ctrl+c when writing to txt file

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The compiler is gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading