I'm trying to add each line of ac file into an array. The contents of files.txt is
first.c
second.c
third.c
fourth.c
I want my code to print each of these lines, add the line to my array, and then print out each entry in my array. Right now it is doing the first part correctly but it is only adding fourth.c to the array. Can someone tell me what is wrong with my code?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i=0;
int numProgs=0;
char* programs[50];
char line[50];
FILE *file;
file = fopen("files.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
//check to be sure reading correctly
printf("%s", line);
//add each filename into array of programs
programs[i]=line;
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (int j=0 ; j<numProgs+1; j++) {
printf("\n%s", programs[j]);
}
fclose(file);
return 0;
}
You need to change
programs[i]=line;
to
programs[i]=strdup(line);
Otherwise all pointers in the programs
array will point to the same location (that is line
).
BTW: if files.txt contains more than 50 lines, you will run into trouble.
you need to allocate new storage for each line, otherwise you only have 1 line buffer to store the file names so only the last one shows up, do this in the while loop:
programs[i] = calloc(strlen(line)+1, 1);
strcpy(programs[i], line);
No need for i
there and to save all pointers to lines in array you must use strdup()
. Just do like that:
programs[numProgs++] = strdup(line);
In the second loop condition must be j < numProgs
.
Add additional condition to your while loop to prevent writing pass the end of array:
while(fgets(line, sizeof line, file)!=NULL && numProgs < 50)
when declaring char *programs[50]
are not valid pointers. So you have allocate memory for every pointer based on every line size. So, try this one.. (Here i am using malloc & strcpy)
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void) {
int i=0;
int numProgs=0;
char* programs[50];
char line[50];
FILE *file;
file = fopen("files.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
//check to be sure reading correctly
printf("%s", line);
//add each filename into array of programs
programs[i]=malloc(sizeof(line));
strcpy(programs[i],line);
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (int j=0 ; j<numProgs+1; j++) {
printf("\n%s", programs[j]);
}
fclose(file);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.