我遇到了分段错误,我怀疑它在while循环中,因为注释while循环允许它以一行读取运行。该程序的目标是采用3个参数,一个文本文件名,一个单词和一个单词来替换第一个单词。所以./this文本旧的NEW将用NEW,全部大写替换所有每行旧单词的第一个实例。根据说明,我只对每行的第一个实例感兴趣。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp; // file pointer
char output[400]; // we put a limit on the size of our string so we don't go overboard
char term[40]; // our term to search for
char newTerm[40]; // the replacement term
char filename[40]; // the name of the file we examine
char curr[150]; // the current line of text read
char currWord[40]; // current token
char *cp; // char pointer
int replaceCounter; // count how many strings were replaced
int i = 0; // index counter
strncpy(filename, argv[1], 40); // assign the first argument to the filename
strcat(filename, ".txt");
strncpy(term, argv[2], 40);
strncpy(newTerm, argv[3], 40);
fp = fopen(filename, "r");
if(fp != NULL)
{
printf("File opened successfully!\n");
while(fgets(curr, 150, fp) != NULL)
{
if((cp = strstr(curr, term)) != NULL);
strncpy(cp, newTerm, strlen(newTerm));
printf("%s\n", curr);
fflush(fp);
}
}
else
{
printf("Error opening file: %s", filename);
return 0;
}
fclose(fp);
return 0;
}
使用Ubuntu和gcc进行编译,所以我没有得到更具体的内容,比如调试。任何帮助表示赞赏。