Search code examples
cinputfwrite

Writing to an output file in C


I am writing a program in C that takes a a command line argument that represents the name of an output file. I then opened the file to write to it. The problem is that when I write something in the command line, it never shows up in the file I was writing to and any text in the file is erased. Here is the code I have for writing to the file from stdin. (fdOut is the FILE * stream that was specified)

 while(fread(buf, 1, 1024, stdin))
 {
   fwrite(buf, 1, 1024, fdOut);
 }

Solution

  • try this code.

    #include "stdio.h"
    
    int main()
    {
            char buf[1024];
            FILE *fdOut;
            if((fdOut = fopen("out.txt","w")) ==NULL)
            {       printf("fopen error!\n");return -1;}
            while (fgets(buf, 1024, stdin) != NULL)
            {
                //   int i ;
                //   for(i = 0;buf[i]!=NULL; ++i)
                //          fputc(buf[i],fdOut);
                     fputs(buf,fdOut);
                //   printf("write error\n");
            }
            fclose(fdOut);
            return 0;
    }
    

    Note : use Ctrl+'D' to stop input.