Chúng ta có thể viết chương trình C để ghi nội dung vào file và thực hiện:
- Đếm số ký tự ghi vào file.
- Đảo ngược các ký tự đã ghi.
Trước tiên, mở file ở chế độ ghi để lưu số ký tự.
Logic nhập dữ liệu vào file:
while ((ch = getchar( ))!=EOF) {// sau khi nhập xong nhấn Ctrl+Z để kết thúc fputc(ch, fp); }
Sử dụng ftell, rewind, fseek để đảo ngược nội dung đã ghi.
Ví dụ
Chương trình C ghi nội dung vào file, đếm ký tự và đảo ngược:
#include<stdio.h> int main( ){ FILE *fp; char ch; int n,i=0; fp = fopen ("reverse.txt", "w"); printf ("enter text press ctrl+z of the end"); while ((ch = getchar( ))!=EOF){ fputc(ch, fp); } n = ftell(fp); printf ( "No. of characters entered = %d\n", n); rewind (fp); n = ftell (fp); printf ("fp value after rewind = %d\n",n); fclose (fp); fp = fopen ("reverse.txt", "r"); fseek(fp,0,SEEK_END); n = ftell(fp); printf ("reversed content is\n"); while(i<n){ i++; fseek(fp,-i,SEEK_END); printf("%c",fgetc(fp)); } fclose (fp); return 0; }
Kết quả
enter text press ctrl+z of the end TutorialsPoint ^Z No. of characters entered = 18 fp value after rewind = 0 reversed content is tnioPslairotuT