w3resource

C Exercises: File read and write using variable


17. File Read/Write Variable

Write a program in C to read from a file into a variable and write a variable's contents into a file.

Sample Solution:

C Code:

#include <stdio.h>

int main(int argc, char **argv) {
  FILE *in, *out;
  int c, str;
   
  in = fopen("i.txt", "r");
  if (!in) {
    fprintf(stderr, "Error opening i.txt for reading.\n");
    return 1;
  }
  out = fopen("o.txt", "w");
  if (!out) {
    fprintf(stderr, "Error opening output.txt for writing.\n");
    fclose(in);
    return 1;
  }
  while ((c = fgetc(in)) != EOF) {
    fputc(c, out);
  }
  fclose(out);
  fclose(in);
  return 0;
}

Sample Output:

Error opening i.txt for reading.

Flowchart:

Flowchart: File read and write using variable.

For more Practice: Solve these Related Problems:

  • Write a C program to read a configuration value from a file and update it dynamically, then write back to the file.
  • Write a C program to read a file into a variable, modify the content, and write the modified content to a new file.
  • Write a C program to load file content into a variable, perform a search-and-replace operation, and save the result.
  • Write a C program to read a file's content into a dynamically allocated string, process the string, and write it back.

Go to:


PREV : Common Directory Tree.
NEXT : Display Last Modification Time.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.