Write a program to reverse the content of a file.
#include<stdio.h> #include"fileinfo.h" #include<string.h> void Reverse_Content_of_File(FILE*,char*); int main() { char file[32]; FILE *fp; printf("Enter File Name = "); scanf("%[^\n]",file); fp = fopen(file,"r"); if(fp == NULL) { printf("file is not present in this directory\n"); return 0; } Reverse_Content_of_File(fp,file); return 0; } void Reverse_Content_of_File(FILE *fp,char* filename) { char *p,ch; int i,j,CharCount = 0; CharCount = Get_Total_Chars(fp); p = malloc(CharCount+1); i = 0; while((ch = fgetc(fp)) != EOF) { p[i] = ch; i++; } p[i] = '\0'; for(i = 0,j = (strlen(p)-1);i < j;i++,j--) { ch = p[i]; p[i] = p[j]; p[j] = ch; } fclose(fp); fp = fopen(filename,"w"); for(i = 0;i < CharCount; i++) { fputc(p[i],fp); } //fputs(p,fp); printf("Reversing Done....\n"); }
Note: File name d1 is present in the current working directory.
cat d1 Lot To Learn BlackBerry Z10 Iphone Incredible India
./a.out Enter File Name = d1 Reversing Done....
cat d1 aidnI elbidercnI enohpI 01Z yrreBkcalB nraeL oT toL
./a.out Enter File Name = d1 Reversing Done....
cat d1 Lot To Learn BlackBerry Z10 Iphone Incredible India