【问题标题】:Reading a file in and perform another task based on that读入文件并基于该文件执行另一项任务
【发布时间】:2021-04-28 16:39:01
【问题描述】:

我目前正在学习 C 中的文件 I/O。我尝试在文本文件中写入字符串,然后尝试读取文件以获取到目前为止写入文件中的字符串。并用它来执行其他任务。写入和读取文件都很好,但是我不能对字符串做任何事情。

这是我的尝试:

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

#define N 100

void fileTest(char str[N], char c) {
    FILE* fp;
    int count = 0;
    
    fp = fopen("assign1.txt", "wt");
    if (fp == NULL) {
        printf("file not found!\n");
        return;
    }
    // writing string to file
    fprintf(fp, "%s", str);
    // reading it back
    fscanf(fp, "%s", str);

    // to ensure every character in str is consistent, lower or upper.
    for (int i = 0; i < strlen(str); ++i) {
        str[i] = tolower((char)str[i]);
    }
    
    // count appearance of `c` in str
    for (int i = 0; i < strlen(str); ++i) {
        if (c == str[i]) {
            count += 1;
        }
    }
    
    printf("character %c appeared %d times", c, count);
    fclose(fp);
}

int main() {
    char str[N], c;
    printf("enter str: ");
    scanf("%s", &str);
    printf("c: ");
    scanf("%c", &c);
    fileTest(str, c);
}

【问题讨论】:

  • 如果这是C代码,这个问题不需要C++标签。
  • 您应该解释编译/运行此代码时会发生什么,以及为什么会出错,即应该发生什么,包括示例输入数据、所需输出和当前输出。
  • 您将不得不详细说明“无法对字符串执行任何操作”的含义。对于发布的代码和测试输入(这也应该是您问题的一部分),您预期的工作流程和输出结果是什么,实际工作流程和输出结果是什么,有什么区别.该信息属于in your question。也就是说,我在对同一源文件调用fwrite 后立即质疑fscanf(fp, "%s", str);,该源文件以写文本模式打开(出于某种原因)。你已经有了字符串,所以,???
  • "file not found!\n" 是无用错误消息的典型示例。给用户一个准确的失败原因:fp = fopen("assign1.txt", "w"); if( fp == NULL ){ perror("assign1.txt"); ... }

标签: c file


【解决方案1】:

你有几个问题。首先,您像这样打开文件:

fp = fopen("assign1.txt", "wt");

这意味着文件已打开以供写入。它不开放阅读。所以你读回它的尝试可能会失败。

但它会失败两次。你这样做:

fprintf(fp, "%s", str);
fscanf(fp, "%s", str);

因此,您必须了解其工作原理。该文件保持一种“当前指针”的运行。写入字符串后,指针设置为文件末尾。当您尝试阅读时(如果您使用 w+ 打开,那么阅读工作),您仍然在错误的地方。你需要回到起点。我认为电话看起来像:

fseek(fp, 0);

这会将当前指针放回到文件的开头。

所以,你需要的改变:

fp = fopen("assign1.txt", "w+");  // open in read-write mode.

// do the fprintf
fseek(fp, 0);
// do the fscanf

我还没有测试过,所以我不能 100% 确定这是完整的。

【讨论】:

  • @Joshph Larson 是的,你说得对,我刚开始学习 C 文件 IO,只是按照教程进行操作,不关注文件模式。使用 fseek(fp, 0, SEEK_SET) 将指针移动到字符串的开头。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2020-04-19
  • 2018-02-15
  • 2021-05-15
  • 2021-01-23
  • 2016-08-14
相关资源
最近更新 更多