Can I use fputs and fgets in file opened in binary

363 Views Asked by At

The data in file is random and both alphabet and numbers.

/**** Program to APPEND one file after another file ****/

#include <stdio.h>
#include <fcntl.h>

int main()
{
    FILE *fp, *fc;
    char data[200];

    fp = fopen("students.DAT", "ab");

    if (fp == NULL)
    {
        printf("Can't open file");
        exit(1);
    }

    fc = fopen("pr1.DAT", "rb");

    if (fc == NULL)
    {
        printf("Can't open file");
        exit(2);
    }

    fseek(fp, 0, SEEK_END);

    while (fgets(data, 199, fc) != NULL)
    {
        fputs(data, fp);
    }
    fputs("\n", fp);

    return 0;
}

Is the use of fputs and fgets in this program OK? If not kindly tell the what to use and why fgets/puts is not ok?

1

There are 1 best solutions below

2
On

In binary mode you should use fread instead of fgets and fwrite instead of fputs. The difference is if you use fwrite function you should provide as arguments:

  1. pointer to the array ( in your case data)
  2. size of each element of the array in bytes
  3. number of elements in the array
  4. pointer to FILE