I have the following C code which writes words given to program to file called "command.txt". If word is "quit" program ends, else it prints the word and writes it to file. However, if the word is "file" it gets the first word on the first line of file by using function getstring() and continues to next loop iteration. This word is then used on this new round and the code goes straight to "else"-branch and should print out the word and write it to file again.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void getstring(char **p) {
char string[100];
char *word = NULL;
FILE *file = fopen("command.txt", "r");
fgets(string, 100, file);
word = strtok(string," \n");
p[0] = word;
fclose(file);
}
void writetofile (char **strarr) {
FILE *file = fopen("command.txt", "a");
fprintf(file, "%s\n", strarr[0]);
fclose(file);
}
int main(void) {
char line[100];
char *word = NULL;
char *strarr[5];
char **p = NULL;
int flag = 0, i;
while (1) {
if (flag == 1) {
flag = 0;
}
else {
printf("Give string: ");
fgets(line, 100, stdin);
word = strtok(line," \n");
strarr[0] = word;
}
if (strcmp(strarr[0], "quit") == 0) {
break;
}
else if (strcmp(strarr[0], "file") == 0) {
p = strarr;
getstring(p);
flag = 1;
continue;
}
else {
printf("Text: %s\n", strarr[0]);
writetofile(strarr);
}
for (i=0; i<5; i++) {
strarr[i] = NULL;
}
}
return 0;
}
The problem is this: if I type in "file" nothing is written to the file. For example, if I give the words "hello", "file" and "world" and then quit the program the printout looks like this:
Give string: hello
Text: hello
Give string: file
Text: hello
Give string: world
Text: world
Give string: quit
command.txt looks like this:
hello
world
So, there's an empty line where should be another "hello". Why is this? Am I missing something obvious here or is this because of the way pointers are used?
Once possible issue is that you are returning a pointer to a local variable in getstring()
:
void getstring(char **p) {
char string[100];
char *word = NULL;
...
word = strtok(string," \n");
p[0] = word; //word points into string[] which is a local
...
}
After your return from getstring()
the local variable string[]
is not longer valid and thus accessing p[0]
later on is undefined behaviour.
To fix this either copy the word into a fixed buffer or allocate the memory for the return string.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다