gpt4 book ai didi

c - 在C中替换文件的特定文本

转载 作者:行者123 更新时间:2023-11-30 19:32:05 25 4
gpt4 key购买 nike

好吧,基本上我要做的就是将文本文件的所有数字更改为美元符号,我知道如何扫描特定字符,但我不知道如何用美元符号替换该特定字符。我不想使用 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);
}

最佳答案

乍一看基本上有两种方法,第一种是使用 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;
}

关于c - 在C中替换文件的特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47487897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com