Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

typing text from keyboard into file

I want to a text from the keyboard and save the input to a file.

This is the code I tried :

    char txt[1024];
        char nomFichier[50];
        char emp[100];
        char empEtNomFichier[150];
        printf("\nDonner le nom du fichier : ");
        scanf("%s", &nomFichier);
        printf("\nDonner l'emplacement du fichier : ");
        scanf("%s", &emp);
            snprintf(empEtNomFichier, sizeof(empEtNomFichier), "%s/%s", emp, nomFichier);
            fichier = fopen(empEtNomFichier,"a+");
            printf(empEtNomFichier);
            printf("\nEnter le text : ");
            while(!feof(stdin)) {
                fgets(txt, 1024, stdin);
                printf(stdin);
            if(strlen(txt) == 0) break;
            fputs(txt, fichier);
}

printf("End.");

The problem is the user finished typing I want to skip the typing and to display the "End." message after the while loop.

Upvotes: 0

Views: 75

Answers (2)

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

How do you know when the user is finished?

The code you posted will continue until the user presses Ctrl+d, which sends an End-of-file to the input stream.

fgets stores the line break, so you need to check if txtcontains nothing but a line break.

Upvotes: 1

Medinoc
Medinoc

Reputation: 6608

Short answer: A line containing only the Ctrl+D character (*n*x) or Ctrl+Z character (Windows)(I think) should end the input and make feof(stdin) return a nonzero value.

Long answer: It's the basic idea, but it's the visible part of the iceberg. Your code contains several errors, some big some minor, when it comes to text input.

Upvotes: 1

Related Questions