使用带“+r”模式的 fopen 替换文件内容的元音

Replacing the vowels of a file's content using fopen with "+r" mode

在下面的代码中我是:

这意味着如果用户输入元音 a,我希望文件的内容最终看起来像这样:Hello, how _re you? Hope you _re h_ving _ gre_t d_y.

我认为在 r+ 模式下重新打开文件可以解决问题,但它不起作用。你能帮我用我已有的东西解决这个问题吗?谢谢!

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


void identifica(void);

int main()
{

FILE *fich;
char file_name[10], vowel = 0, c = 0;

printf("Please enter the file name:\n");
gets(file_name);

fich = fopen(file_name, "w");

fputs ("Hello, how are you? Hope you are having a great day.", fich);

printf("What vowel do you want to reaplce with '_'?\n");
vowel = getchar ();

fclose(fich);
fich = NULL;

fich = fopen(file_name, "r+");

while ((c = fgetc(fich)) != EOF)
{
    if (c == vowel)
    {
        fputs ("_",fich);
    }
}

fclose(fich);
fich = NULL;

return 0;
}

你应该在语句fputs("_",fich);之前加上fseek(fich, -1, SEEK_CUR);。读取字符c后,需要后退一个位置来替换正确的字符。替换字符后,您可以使用 fseek(fich, 0, SEEK_CUR); 返回当前位置。以下代码可以正常工作 -

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


void identifica(void);

int main()
{

FILE *fich;
char file_name[10], vowel = 0;
int c = 0;

printf("Please enter the file name:\n");
gets(file_name);

fich = fopen(file_name, "w");

fputs ("Hello, how are you? Hope you are having a great day.", fich);

printf("What vowel do you want to reaplce with '_'?\n");
vowel = getchar ();

fclose(fich);
fich = NULL;

fich = fopen(file_name, "r+");

while ((c = fgetc(fich)) != EOF)
{
    if (c == vowel)
    {
        fseek(fich, -1, SEEK_CUR);
        fputs("_",fich);
        fseek(fich, 0, SEEK_CUR);
    }
}

fclose(fich);
fich = NULL;

return 0;
}

注意:fgetc() return 是 int,不是 char;它必须 return 每个有效的 char 值加上一个单独的值 EOF。正如所写,您无法可靠地检测到 EOF。如果 char 是无符号类型,您将永远找不到 EOF;因此,我将 c 替换为类型 int.

在 C 中,当您以更新模式打开文件时(例如使用 r+),您将有 两个 个位置,一个用于读取,一个用于写入。读取本身不会(必然)移动写指针,而写入不会(必然)移动读指针。按照标准定义,在读写之间切换时必须使用 fseekfflush(例如,参见 .

所以你需要写...

    fseek(fich, -1, SEEK_CUR);
    fputs("_",fich);
    fseek(fich, 0, SEEK_CUR);