Nov 26, 2016

C Programming #91: fileio - fprintf, fscanf

C Programming #91: fileio - fprintf, fscanf

Similarly how there was formatted print function for stdio, there are function that could be used with file. We could apply all the formatting tricks that was used for printf and scanf.


fprintf

int fprintf(FILE *stream, const char *format, ...);

First argument is pointer to FILE. Rest of it is like printf. Small example to demo, by writing 'a', 10 and "hello" into a file.

#include <stdio.h>
#include <errno.h>
int main()
{
   FILE *fp;

   fp = fopen("/tmp/test_file", "w+");

   if(fp != NULL) {
      printf("file opened successfully fp is %p\n", fp);
   }else {
      printf("fopen failed with errorno %d\n", errno);
   }

   fprintf(fp,"%c%d%s", 'a', 10, "hello");


   if(fclose(fp) != EOF) {
      printf("file closed successfully");
   }else {
      printf("fclose failed with errorno %d\n", errno);
   }
   fp = NULL;

  return 0;
}
file opened successfully fp is 0x2337010
file closed successfully
# cat /tmp/test_file
a10hello

fscanf

int fscanf(FILE *stream, const char *format, ...);

Now lets read those there variable using fscanf.

#include <stdio.h>
#include <errno.h>
int main()
{
   FILE *fp;
   char c;
   int i;
   char s[100];

   fp = fopen("/tmp/test_file", "r");

   if(fp != NULL) {
      printf("file opened successfully fp is %p\n", fp);
   }else {
      printf("fopen failed with errorno %d\n", errno);
   }

   fscanf(fp, "%c%d%s", &c, &i, s);
   printf("c is %c, i is %d and s is %s\n", c, i, s);

   if(fclose(fp) != EOF) {
      printf("file closed successfully");
   }else {
      printf("fclose failed with errorno %d\n", errno);
   }
   fp = NULL;

  return 0;
}

Links

No comments :

Post a Comment