【问题标题】:Replacing specific text of a file in C在 C 中替换文件的特定文本
【发布时间】:2026-02-14 07:40:02
【问题描述】:

好的,所以基本上我要做的就是将文本文件的所有数字更改为美元符号,我知道如何扫描特定字符,但我不知道如何用美元符号替换该特定字符。我不想使用 fseek 或任何库命令,我该如何进行?为什么我的代码不起作用?

#include<stdio.h>
main()
{
FILE* fptr;
char filename[50];
char string[100];
int i;
printf("Enter the name of the file to be opened: ");
scanf("%s",filename);
fptr=fopen(filename,"w");
if(fptr==NULL)
{
    printf("Error occurred, try again.");
    return 0;
}
fgets(string,"%s",fptr);
do
{
    if(string[i]>='1' && string[i]<='9')
    {
        string[i]='$';
    }
}
while(i!=100);
fclose(fptr);
}

【问题讨论】:

  • fgets(string,100,fptr)
  • 您意识到您实际上并没有将任何更改写回文件,对吧?
  • int i; 未初始化。建议:使用 for() -循环而不是 do{...}while();
  • 您打开文件进行写入;没有要从文件中读取的数据,因为您只是截断了它。此外,即使有任何数据要读取,您也无法从打开的文件中读取。您可以将输入文件(以只读方式打开)复制到新文件(仅以写入方式打开),并将数字替换为美元符号,或者您可以打开文件以进行读取和写入 ("r+") 和那么您将不得不使用fseek() 来处理文件,至少当您需要将数字更改为美元符号时。请注意,您必须在读取和写入之间进行搜索。

标签: c string file


【解决方案1】:

乍一看基本上有两种方法,第一种是使用 fseek() 第二种方法是读取整个文件并将字符替换为您的标准,最后一次写入。您可以根据需要选择其中一种方法。对于大文件,你应该更喜欢前者,对于小文件,你可以更喜欢后者。

这是前者的示例代码:

#include <stdio.h>

int main() {
    // Open the file
    FILE *fptr = fopen("input.txt", "r+");
    if (!fptr) {
        printf("Error occurred, try again.");
        return -1;
    }
    int c;
    // Iterate through all characters in a file
    while ((c = getc(fptr)) != EOF) {
        // Check if this current character is a digit?
        if (c >= '0' && c <= '9') {
            // Go one character back
            if (fseek(fptr, -1, SEEK_CUR) != 0) {
                fprintf(stderr, "Error while going one char back\n");
                return -1;
            }
            // Replace the character with a '$'
            if (fputc('$', fptr) == EOF) {
                fprintf(stderr, "Error while trying to replace\n");
                return -1;
            }
        }
    }
    // Flush the changes to the disk
    if (fflush(fptr) != 0) {
        fprintf(stderr, "Error while flushing to disk\n");
        return -1;
    }
    // Close the file
    fclose(fptr);
    return 0;
}

【讨论】: