替换文件中的特定文本C
问题描述:
好吧,基本上我所要做的就是将文本文件的所有数字都更改为美元符号,我知道如何扫描特定字符,但我坚持要如何替换美元符号的特定字符。我不想使用fseek或任何库命令,我该如何继续,为什么我的代码不工作?替换文件中的特定文本C
#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;
}
'与fgets(字符串,100,FPTR)' – coderredoc
你明白了你不实际写入任何更改回原来的文件,对不对? – dbush
'int i;'是未初始化的。建议:使用for()-loop而不是'do {...} while();'。 – wildplasser