【问题标题】:Rewinding a file pointer [closed]倒带文件指针[关闭]
【发布时间】:2017-04-08 13:03:16
【问题描述】:

我知道你可以只关闭一个文件,但我想尝试使用倒带功能,但我遇到了一个奇怪的错误。首先我读取一个文件并计算字数,然后我尝试倒带(只是为了练习文件处理),输出以下错误:看起来问题出在最后一行代码。

https://snag.gy/63oqwC.jpg

代码如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int readFile(FILE  *f, char *fileName) {
    int count = 0;
    char ch;

    f = fopen(fileName, "r");
    if ( f == NULL ) {
        printf("Cannot open %s file, please verify it's in the right location\n", fileName);
    }

    while ( (ch = fgetc(f) ) != EOF ) {
        if ( ch == '\n' ) {
            count++;
        }

    }
    printf("The count number is %d", count);
    return count;

}


int main() {

FILE *wordInput = NULL;
    int i, j, k = 0;
    char c;
    char *point; // pointer that points to a word
    char **dictionary; // pointer that points to variable point
    int count = 0;
    int dictChoice; // which dictionary are they picking
    int numLetters = 4; // number of letters for each word

    FILE *fPoint = NULL;


    char *name = "smallDictionary.txt";

    readFile(wordInput, name);

    rewind(wordInput);


    return 0;
}

【问题讨论】:

  • 我去掉了 close 语句,它仍然可以这样做
  • C 是按值传递。 wordInput in main() 被初始化为 NULL 并且永远不会改变它的值。
  • 顺便说一句,fgetc() 返回 int 而不是 char
  • 能够读取 256 个不同的字符,并且能够返回一个单独的值来识别这 8 位之上的文件结尾是不够的。
  • "that's not working" 到底是什么意思?你如何测试?会发生什么?

标签: c file pointers


【解决方案1】:
int readFile(FILE *f, char *fileName)

由于您尝试修改FILE 指针,因此您需要将指针传递给指向FILEFILE ** 的指针。将函数头改为

int readFile(FILE **f, char *fileName)

在调用者中,您需要传递一个指向FILE * 对象的指针:

FILE *pf;
int n = readFile(&pf, "filename.txt");

另外,当您完成文件操作后,请立即致电fclose

fclose(pf);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多