Search code examples
cfilefgets

How do I read user input and write it to a .txt. file?


I need to be able to prompt the user to input text, which is then taken and inputed into a text file. It then stops reading once the user enters CRTL-D/fputs returns NULL.

I can open a file and use fprintf to write to it, but now I need to write to the file using user input. I don't really know where to start.

I know how to read a .txt file and print its contents to the terminal using fputs, but writing to one through the terminal is too confusing for me...

int main(int argc, char *argv[]) {
FILE *f;

  f = fopen(argv[1], "w");
  if (errno) {
      perror("Error opening file.");
      exit(1);
  }

  fprintf(f, "Hello, Jake.\n");
  fclose(f);
}

I need a while loop that ends once the fputs or feof returns NULL.

If at any point I have said something that doesn't make sense, it's because I am confused. Learning C for uni is driving me nuts :(


Solution

  • You should create and open the file first. Then in a loop, start reading input with fgets(). In every iteration, write what you just read to the file. When the user inputs EOF, then close the file and you are done.

    Example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define BUFFERSIZE 64
    
    int main(void)
    {
    
        FILE *fp;   /* File pointer*/
        char filename[] = "output.txt";
    
        /* Creating (open) a file*/
        fp = fopen(filename, "w");
        /* Check file created or not*/
        if(fp == NULL)
        {
            printf("File was not created!!!\n");
            exit(0); /* Exit from program*/
        }
    
        printf("File created successfully\n");
        /* Read from input */
        char buffer[BUFFERSIZE];
        while(fgets(buffer, BUFFERSIZE, stdin)) /* Break with ^D or ^Z */
        {
            /* Remove trailing newline */
            buffer[strcspn(buffer, "\n")] = 0;
            /* Writting into file*/
            fprintf(fp, "%s\n", buffer);
        }
    
        printf("Data written successfully.\n");
        fclose(fp);
        return 0;
    }
    

    Output:

    Georgioss-MBP:gsamaras$ gcc main.c
    Georgioss-MBP:gsamaras$ ./a.out 
    File created successfully
    Hello Stack Overflow
    You are the best!
    Data written successfully.
    Georgioss-MBP:gsamaras$ cat output.txt 
    Hello Stack Overflow
    You are the best!
    

    Note: I removed the newline fgets stores.