當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ ftell()用法及代碼示例

C++ 中的ftell() 函數返回文件指針的當前位置。

ftell()原型

long ftell(FILE* stream);

ftell() 函數將文件流作為其參數,並將給定流的文件位置指示符的當前值作為 long int 類型返回。

它在<cstdio> 頭文件中定義。

參數:

stream : 返回當前位置的文件流。

返回:

成功時,ftell() 函數返回文件位置指示符。否則,它返回 -1L。

示例:ftell() 函數的工作原理

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int pos;
    char c;
    FILE *fp;
    fp = fopen("file.txt", "r");
    if (fp)
    {
        while ((c = getc(fp)) != EOF)
        {
            pos = ftell(fp);
            cout << "At position " << pos << ", character is " << c << endl;
        }
    }
    else
    {
        perror("Error reading file");
    }
    fclose(fp);
    return 0;
}

運行程序時,輸出將是:

At position 1, character is P
At position 2, character is r
At position 3, character is o
At position 4, character is g
At position 5, character is r
At position 6, character is a
At position 7, character is m
At position 8, character is i
At position 9, character is z
At position 10, character is .
At position 11, character is c
At position 12, character is o
At position 13, character is m

相關用法


注:本文由純淨天空篩選整理自 C++ ftell()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。