fpipe with ls writing into string array wrong output
-
i=0; while (fgets( line, sizeof line, fpipe)) { fprintf(stdout, "LINE %d: %s \n", i, line); files[i] = line; i++; } for(i=0; i<limit; i++) { fprintf(stdout, "filename %d:%s \n", i, files[i]); }
fpipe contains an ls command, listing my 3 files in a directory, BUT:
The outputs differ quite much! Within the while loop, I get all the lines from ls without a problem!But within the for loop, i only get the last one (printing my string array)! Watch this:
LINE 0: . LINE 1: .. LINE 2: .DS_Store LINE 3: testfile.o filename 0: testfile.o filename 1: testfile.o filename 2: testfile.o filename 3: testfile.o
Why is it like that?
PS: You can also answer in german, forgot that this board is german!
-
You can not copy an array via operator=. This just sets all the
files[i]
to the address ofline
. Thus, you only see the content ofline
when you print thefiles[i]
.
Usually your compiler should not allow this if thefiles[i]
were char-Arrays. Isfiles
a*char[]
?
Nonetheless: You need to usestrcpy
to copy char-Arrays. And thefiles[i]
need to either be char-Arrays themselves or point to a char-Array (you can usemalloc
to allocate a new array with the size of the string you would like to copy. Don't forget an extra byte for the null terminator!)
-
You have to copy the strings from your line. Otherwise the line is overwritten in any loop again and again. At the moment you only store a pointer to the same line in any entry of your pointer array (?), which leads at the end to the effect you described.
-
Thank you guys, that worked perfectly. It's more than 10 years ago that I used to deal with C-Strings! Thanks to remind me how to use it.
Solved, can be closed.
-
SeppJ schrieb:
Nonetheless: You need to use
strcpy
to copy char-Arrays.Müssen muss er nicht unbedingt. Es geht auch ohne.
struct Line {char x[100];} line; i=0; while (fgets( &line, sizeof line, fpipe)) { fprintf(stdout, "LINE %d: %s \n", i, &line); *(struct Line*)files[i] = line; i++; }