【问题标题】:unsure of fseek syntax in c不确定 c 中的 fseek 语法
【发布时间】:2015-09-16 10:54:42
【问题描述】:

我只是想知道这段代码为什么你必须在 fseek(fptr, -1, SEEK_END); 结束前的 1 个位置开始阅读,以及为什么你必须返回 2 个位置而不是 fseek(fptr, -2, SEEK_CUR); 中的 1 个位置

#include <stdio.h>
#include <stdlib.h>
FILE * fptr;

int main()
{
    char letter;
    int i;

    fptr = fopen("/Users/Dan/Documents/Coding/alpbkw/alphabet.txt", "w+");

    if (fptr == 0)
    {
        printf("there was an error opening the file");
        exit(1);
    }

    for (letter = 'A'; letter <= 'Z'; letter++) //knows how to count up the alphabet
    {
        fputc(letter,fptr); //note syntax. fputc puts characters in a file
    }

    puts("characters have been written in the file");

    fseek(fptr, -1, SEEK_END); //looks in fptr, starts from 1 byte before the end. the -1 is the offset. this statement shows where it starts, not how it cycles. i think end of file doesnt actually have a letter printed on it, its a placeholder or something
    printf("here is the file backwards\n");

    for (i=26;i>0;i--) //starting from the last and counting backwards. goes through 26 times as expects 26 letters
    {
        letter = fgetc(fptr); //gets the letter it is currently on and reads it
        fseek(fptr, -2, SEEK_CUR); //backs up 2 places, if back up twice you will only print z's.
        printf("the next letter is %c.\n", letter);
    }
    fclose(fptr);
    return 0;
}

【问题讨论】:

    标签: c fseek


    【解决方案1】:

    假设您在文件中的位置 X,然后您读取了一个将位置移动到位置 X+1 的字符,然后您想转到 X 之前的字符,即位置 X-1。从 X+1 位置到 X-1 位置,您需要寻求多少?你需要寻找-2个职位。

    【讨论】:

    • 哦,所以当您阅读时,您可以将光标移到正在阅读的内容上。谢谢!
    • 如果您仍然对第一个问题感到疑惑:fseek( fptr, 0, SEEK_END) 会将指针 刚好超过 文件的最后一个字符,因此您需要 fseek( fptr, -1, SEEK_END)在正确的位置读取最后一个字符。
    • 如果您在进行大量fseek() 调用以及fgetc() 和/或小型fread() 调用时,最好使用setbuf()setvbuf() 禁用缓冲;或使用open()lseek()read() 或仅使用pread()FILE *-based IO 默认是缓冲的,缓冲区大小通常是 8KB 左右。但是fseek() 将使缓冲区无效,导致您的下一个小的fread()fgetc()(单字节读取)很可能会一次又一次地读取整个8KB。
    • @AndrewHenle 好点,但只是为了平衡它:如果文件(或通常)相对较小,这样(大部分)它适合所述缓冲区,坚持缓冲函数可能是更好的是 fseek()s 应该只在缓冲区中重新定位一个指针。
    • @TripeHound - 是的,但如果整个文件可以放入普通的 FILE * 缓冲区,我敢说你最好把它读入 char[]并直接访问字节。但话又说回来,当性能真的很重要时,我不喜欢使用基于FILE * 的 IO 例程的 stdio 集。鉴于大多数操作系统都有页面缓存,stdio 缓冲区很容易变得多余,实际上会减慢速度。但在大多数情况下,最好的代码是开发人员能够识别和理解的代码。
    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2021-04-07
    • 2010-09-27
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多