This blog is under construction

Saturday 29 June 2013

C program to read data from one file and write it another file

Write a C program to read data from one file and write it to another file.


  #include <stdio.h>
  int main() {
        FILE *fp1, *fp2;
        int id, age, salary;
        char name[100];

        /* open "file2.txt" file in read mode */
        fp1 = fopen("file2.txt", "r");

        /* open "file1.txt" in write mode */
        fp2 = fopen("file1.txt", "w");

        fprintf(fp2, "ID   Age  Salary  Name\n");
        fprintf(fp2, "--------------------------------\n");
        while (!feof(fp1)) {
                /* read the inputs from file2.txt */
                fscanf(fp1, "%d%d%d", &id, &age, &salary);
                fgets(name, 100, fp1);

                /* print the above read outputs to file1.txt */
                fprintf(fp2, "%-5d%-5d%-7d%s", id, age, salary, name);
        }

        /* close both the files */
        fclose(fp1);
        fclose(fp2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat file2.txt 
  1 30 10000 Annie
  2 40 10456 Bill
  3 26 15000 Rahul
  4 45 12345 John
  5 54 11111 Jacob

  jp@jp-VirtualBox:~/$ ./a.out

  jp@jp-VirtualBox:~/$ cat file1.txt 
  ID   Age  Salary  Name
  --------------------------------
  1    30   10000   Annie
  2    40   10456   Bill
  3    26   15000   Rahul
  4    45   12345   John
  5    54   11111   Jacob
  5    54   11111   Jacob
  


No comments:

Post a Comment