0

How can I write and create the file, append if the file exists, then display all string file text? I can't append the content to at the end of file text, then display all strings. Thank for reading!

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv) {
char c, filename[100], content[100];
FILE *fptr;
printf("File name: ");
scanf("%s", filename);

printf("Enter content: ");
gets(content);
if ((fptr = fopen(filename, "r")) == NULL)
{
    fptr = fopen(fptr, "w");
   fprintf(fptr,"%s", content);    
}
else{
     fptr = fopen(fptr, "a");
     fprintf(fptr,"%s", content);
}

c = fgetc(fptr);
while (c != EOF)
{     
    printf ("%c", c);
    c = fgetc(fptr);
} 
fclose(fptr);
return 0;
}
An Mạnh
  • 31
  • 6
  • 1
    Please read how to create a [mcve] -- you just write "*I can't do [foo]*", instead please include your input, your expected output and your actual output ([edit your question](https://stackoverflow.com/posts/50138926/edit) to include this information) –  May 02 '18 at 16:04
  • 2
    One thing to note anyways: [**never use `gets()`**](https://stackoverflow.com/q/1694036/2371524) and never use `scanf("%s", ...)` either which has the same flaw. For `scanf()`, use a *field width*, like in your example: `scanf("%99s", filename);`, or, better yet, `fgets()`. See also my [beginners' guide away from `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). –  May 02 '18 at 16:06
  • 1
    And remember that [`fgetc`](http://en.cppreference.com/w/c/io/fgetc) returns an **`int`**. This is rather important for that `EOF` check actually. – Some programmer dude May 02 '18 at 16:12
  • 1
    this `fptr = fopen(fptr, "w");` doesn't make any sense as `fopen()` first argument is of `const chart*` type not `FILE*`. – Achal May 02 '18 at 16:18
  • Continuing a little on the comment by @achal: Once you fixed that, if your read-only open succeeded then you have a *resource leak* since you don't close the already opened file-handle. – Some programmer dude May 02 '18 at 16:30
  • regarding: `scanf("%s", filename);` 1) always check the returned value (not the parameter values) to assure the operation was successful. (in this case, the returned value should be 1). 2) when using the '%s' and/or '%[...]' input format specifiers, always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer to avoid any buffer overflow because those input specifiers always append a NUL byte to the input. – user3629249 May 04 '18 at 17:39
  • when calling `fopen()`, always check (!=NULL) the returned value to assure the operation was successful. – user3629249 May 04 '18 at 17:41
  • when writing the signature for the `main()` function, if the parameters are not going to be used, then use the signature: `int main( void )` – user3629249 May 04 '18 at 17:43
  • it is a poor programming practice to include header files those contents are not used. Suggest removing the `#include` statements for `unistd.h` and `string.h` – user3629249 May 04 '18 at 17:45
  • the file is being opened for `write` or `append` then it is being written to. At that time, the logical `file pointer` will be pointing just past the last character in the file. So must be moved back to the beginning of the file, so the calls to `fgetc()` will work. Suggest using `rewind()` for that purpose, before the first call to `fgets()` – user3629249 May 04 '18 at 17:49

2 Answers2

0

If you want to open a file for reading and to also append to it, you can do that with just one call to fopen by using the mode a+.

fptr = fopen(filename, "a+");
if (fptr == NULL)
{
   // Handle not being able to open the file
}

If the file doesn't exist, it will create it. The position for reading will be at the beginning of the file, but anything you write to it will be at the end.

Chris Turner
  • 8,082
  • 1
  • 14
  • 18
0

There are lot of bugs as mentioned by others in comments. I tried to explain in comments, read it carefully.

int main(int argc, char** argv) {
        char filename[100], content[100];
        FILE *fptr;

        printf("Enter content: \n");
        fgets(content,sizeof(content),stdin); /*use fgets() instead of gets()*/

        printf("File name: ");
        scanf("%s", filename);


        if ((fptr = fopen(filename, "r")) == NULL) {/*if doesn't exist */
                fptr = fopen(filename, "w"); /*create it */
                fprintf(fptr,"%s", content); /* and write it */
        }
        else{
                /* it should be a+ if you want to read, as you are doing using fgetc() */
                fptr = fopen(filename, "a+");/*if exist, write at end of file */
                fprintf(fptr,"%s", content);/* write at end */
        }
        rewind(fptr);/* move the fptr to beginning to read further */
        int c = 0; /* fgetc() returns integer */
        while( (c = fgetc(fptr))!= EOF) {     
                printf ("%c\n", c);
        } 
        fclose(fptr);
        return 0;
}

Use fgets() instead of gets(). Read here Why is the gets function so dangerous that it should not be used?

Achal
  • 11,821
  • 2
  • 15
  • 37