Write to file text from terminal using fgets()

Issue

#include <stdio.h> 
#include <cstdio>
int main(int argc, char* argv[]) {
    char buff[512];
    int desc;
    int lb;
    desc = open(argv[1], O_WRONLY);
    if(desc == -1) {
        perror("error");
        exit(1);
    }
    while(lb=fgets(buff,512,stdin) > 0) {
        write(desc,buff,lb);

    }
    
}

In C on linux I have to write to a file passed as an argv text from terminal written by user, using fgets().The program is supposed to work in a loop and if user writes "end" the program stops.
I guess now the program is going to write to the file text from the stdin, not really sure how to end the program while the "end" condition.

Solution

"Not really sure how to get text from terminal into the buffer "

fopen() is a better option (per comments on open()). The following assumes a text file, and that a valid filespec is on the command line. It will read until it sees ‘end’, then capture that as the last line…

( Will also exit on the following: for UNIX systems Ctrl+D, or Windows Ctrl+Z. )

#define INSTRUCTIONS "Entered text will be written to file %s.\n\
When finished with desired input press '<enter>end'.\n\
This will close and save the file, and exit the program.\n\
Begin Here:\n"
 

int main(int argc, char *argv[])
{
    char buffer[80] = {0};
    if(argv < 1) 
    {
        printf("missing filespec in command line\nHit any key to exit.");
        getchar();
        return 0;
    }
    printf(INSTRUCTIONS, argv[1]);
    FILE *fp = fopen(argv[1], "w");
    if(fp)
    {
        while(fgets(buffer, sizeof buffer, stdin))//reads until EOF
        {
            fputs(buffer, fp);
            buffer[strcspn(buffer, "\n")] = 0;//clear newline
            //looks for a new line containing only end\n
            if(strcmp(buffer, "end") == 0)
            {
                fclose(fp);
                break;
            }
        }
    }
    return 0;
}
    

Answered By – ryyker

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published