C語言中fseek()與rewind()的比較
fseek()
C語言中的fseek()函式用於將檔案指標移動到特定位置。偏移量和流是函式引數中給定的指標目標。如果成功,則返回零,否則返回非零值。
以下是C語言中fseek()函式的語法:
int fseek(FILE *stream, long int offset, int whence)
以下是fseek()函式中使用的引數:
stream − 這是用於標識流的指標。
offset − 這是從位置開始的位元組數。
whence − 這是新增偏移量的起始位置。
whence由以下常量之一指定。
SEEK_END − 檔案結尾。
SEEK_SET − 檔案開頭。
SEEK_CUR − 檔案指標的當前位置。
以下是一個C語言中fseek()函式的示例:
假設我們有一個名為“demo.txt”的檔案,其內容如下:
This is demo text! This is demo text! This is demo text! This is demo text!
現在讓我們看看程式碼。
示例
#include<stdio.h>
void main() {
FILE *f;
f = fopen("demo.txt", "r");
if(f == NULL) {
printf("
Can'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
在上面的程式中,使用fopen()開啟檔案“demo.txt”,並使用fseek()函式將指標移動到檔案結尾。
f = fopen("demo.txt", "r");
if(f == NULL) {
printf("
Can't open file or file doesn't exist.");
exit(0);
}
fseek(f, 0, SEEK_END);rewind()
rewind()函式用於將檔案位置設定為給定流的開頭。它不返回值。
以下是C語言中rewind()函式的語法:
void rewind(FILE *stream);
以下是一個C語言中rewind()函式的示例:
假設我們有一個名為“new.txt”的檔案,其內容如下:
This is demo! This is demo!
現在,讓我們看看示例。
示例
#include<stdio.h>
void main() {
FILE *f;
f = fopen("new.txt", "r");
if(f == NULL) {
printf("
Can'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
在上面的程式中,使用fopen()開啟檔案,如果指標變數為空,則會顯示“無法開啟檔案”或“檔案不存在”。rewind()函式將指標移動到檔案的開頭。
f = fopen("new.txt", "r");
if(f == NULL) {
printf("
Can't open file or file doesn't exist.");
exit(0);
}
rewind(f);
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP