C File I/O Operations : fputs()

The fputs() function is used to writes strings into a file. The basic syntax of function is :
 int fputs(const char *str, FILE *fp);
Where str is the string pointer which needs to be written and fp is file pointer. On success the function will return non-negative value and on error it returns EOF.

C Example Program :
 #include <stdio.h>

int main() {
  char str[] = ("Hello world, This is Sample Text.\n");
  FILE *fp = fopen("myfile.txt", "w");
  fputs(str, fp);
  fclose(fp);
  printf("String written succesfully into myfile.txt.\n");
  return 0;
}
Output :

String written succesfully into myfile.txt.

The above code writes the string contained by the character array str into myfile.txt. Now with the below code we can read the content of the file.
 #include <stdio.h>

int main() {
  char str[50];
  FILE *fp;
  fp = fopen("myfile.txt", "r");
  while((fgets(str, 50, fp)) != NULL) {
    printf("%s", str);
  }
  return 0;
}
Output :

Hello world, This is Sample Text.

At above code fgets() function is used.

Topics :