fseek()
ย้าย file pointer ไปตำแหน่งเฉพาะ (offset, whence) คืน 0 ถ้าสำเร็จ
ไวยากรณ์: int fseek(FILE *stream, long int offset, int whence)
whence: SEEK_END (ท้ายไฟล์), SEEK_SET (ต้นไฟล์), SEEK_CUR (ตำแหน่งปัจจุบัน)
ตัวอย่าง fseek()
ไฟล์ "demo.txt" มีข้อความยาว
#include <stdio.h>
void main() {
FILE *f;
f = fopen("demo.txt", "r");
if(f == NULL) {
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
fseek(f, 0, SEEK_END);
printf("The size of file: %ld bytes", ftell(f));
getch();
}ผลลัพธ์
The size of file: 78 bytes
rewind()
ตั้งตำแหน่ง file pointer ไปต้นไฟล์ (เหมือน fseek(stream, 0, SEEK_SET)) ไม่คืนค่า
ไวยากรณ์: void rewind(FILE *stream);
ตัวอย่าง rewind()
#include <stdio.h>
void main() {
FILE *f;
f = fopen("new.txt", "r");
if(f == NULL) {
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
rewind(f);
fseek(f, 0, SEEK_END);
printf("The size of file: %ld bytes", ftell(f));
getch();
}ผลลัพธ์
The size of file: 28 bytes
rewind() ย้าย pointer ไปต้นไฟล์ ก่อน fseek() หาขนาด