问题
The function is big but I have take some code from that function and I have a question that how to find that specific name from text file? I am not sure.
for (option = 1; option <= sizeof(listing)/sizeof(char *); ++option)
printf("%d. Your %s:\n", option, listing[option-1]);
fputs("Select your choice to update: ", stdout);
if ((scanf("%d", &option) != 1) || (option < 1) || (option > sizeof(listing)/sizeof(char *)))
{
puts("invalid choice");
fclose(fr3);
return -1;
}
int one_by_one;
printf("Enter new name to update: ");
scanf("%s",&updated_name);
for (one_by_one=0; file_text[one_by_one] != '\0'; one_by_one++)
{
while(file_text[one_by_one] == updated_name)
{
one_by_one++;
if (one_by_one == strlen(updated_name))
{
found=1;
printf("It is found: \n");
break;
}
}
}
回答1:
If you are trying to search and update any name, you should take a line from source file using fgets() and store in a temporary char array. Then you can use string function like strstr() function to find the name in that line, if found replace it otherwise continue.
You can refer to this link for some help.
回答2:
regarding:
scanf("%s",&updated_name);
This will allow the user to overrun the buffer: updated_name. Suggest including a MAX CHARACTERS modifier that is 1 less than the length of updated_name[] because %s always appends a NUL byte to the input. This will avoid a buffer overflow and the resulting undefined behavior.
regarding:
while(file_text[one_by_one] == updated_name)
strings cannot be compared with a C operator. Suggest using strcmp(). Also, this is comparing a string to a single character, which does not work.
to find a sub string in a string, strongly suggest using: strstr()
来源:https://stackoverflow.com/questions/62259603/how-to-find-and-take-specific-word-from-text-file-in-c