我只是不確定爲什麼我的replaceWord
沒有進入文件,我已經使用了所有的註釋等,等等。我只是試圖用從命令行參數收到的文本替換。我知道我可能離我很遠,我只是尋找一個相對簡單的方法來做到這一點。用另一個替換字符串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argc != 4) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf("usage: %s filename\n", argv[0]);
}
else
{
// We assume argv[1] is a filename to open
char* wordReplace = argv[1];
char* replaceWord = argv[2];
FILE *file = fopen(argv[3], "r");
/* fopen returns 0, the NULL pointer, on failure */
if (file == 0)
{
printf("Could not open file\n");
}
else
{
char string[100];
int len = 0;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ((fscanf(file, "%s", string)) != EOF)
{
len = strlen(string);
printf("%s\n", string);
if(strcmp(string, wordReplace) == 0){
//fseek (file, (-strlen(string) + 1), 1);
//fputc(*replaceWord,file);
//replaceWord++;
//strcpy(string, replaceWord);
fprintf(file,"%s",replaceWord);
fputs(replaceWord, file);
printf("\n%d\n", len);
}
}
fclose(file);
}
}
printf("\n");
return 0;
}
您已經以讀取模式打開文件。以讀寫模式打開文件,即「r +」。 – 2012-04-25 04:29:22
寫入臨時文件;刪除原始文件;將臨時文件重命名爲原始文件 – BLUEPIXY 2012-04-25 07:55:53