This C Program reverses the contents of a file and print it.
Here is source code of the C Program to reverse the contents of a file and print it. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
* C Program to Reverse the Contents of a File and Print it
long count_characters(FILE *);
void main(int argc, char * argv)
char ch, ch1;
FILE *fp1, *fp2;
if (fp1 = fopen(argv, "r"))
printf("The FILE has been opened...\n");
fp2 = fopen(argv, "w");
cnt = count_characters(fp1); // to count the total number of characters inside the source file
fseek(fp1, -1L, 2); // makes the pointer fp1 to point at the last character of the file
printf("Number of characters to be copied %d\n", ftell(fp1));
ch = fgetc(fp1);
fseek(fp1, -2L, 1); // shifts the pointer to the previous character
printf("\n**File copied successfully in reverse order**\n");
// count the total number of characters in the file that *f points to
long count_characters(FILE *f)
fseek(f, -1L, 2);
long last_pos = ftell(f); // returns the position of the last element of the file
$ gcc file12.c $ cat test2 The function STRERROR returns a pointer to an ERROR MSG STRING whose contents are implementation defined. THE STRING is not MODIFIABLE and maybe overwritten by a SUBSEQUENT Call to the STRERROR function. $ a.out test2 test_new The FILE has been opened.. Number of characters to be copied 203 **File copied successfully in reverse order** $ cat test_new .noitcnuf RORRERTS eht ot llaC TNEUQESBUS a yb nettirwrevo ebyam dna ELBAIFIDOM ton si GNIRTS EHT .denifed noitatnemelpmi era stnetnoc esohw GNIRTS GSM RORRE na ot retniop a snruter RORRERTS noitcnuf ehT $ ./a.out test_new test_new_2 The FILE has been opened.. Number of characters to be copied 203 **File copied successfully in reverse order** $ cat test_new_2 The function STRERROR returns a pointer to an ERROR MSG STRING whose contents are implementation defined. THE STRING is not MODIFIABLE and maybe overwritten by a SUBSEQUENT Call to the STRERROR function. $ cmp test test_new_2
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
« Prev - C Program to Replace Bits in Integer x from Bit Position a to b from Another Integer y in C
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Computer Science Books
- Apply for Computer Science Internship
- Practice BCA MCQs
- Apply for C Internship
- Buy C Books