【发布时间】: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"); ... }