Im trying to read each line from a file, and store those values in a pointer array. Im new to C so sorry for my scrappy code.
I tried reading char by char, put them in a string, and then "store" that string in the pointer array, since it looked like a simple solution, but im having trouble with memory allocations.
Here is my code:
char *files[100];
char buffer;
int r, i, j;
char temp[100];
int fd=open(argv[1], O_RDONLY);
i=j=0;
while(read (fd, &buffer, 1) > 0) {
if(buffer != '\n') {
temp[i] = buffer;
}
else{
files[j]=temp;
j++;
i=0;
continue;
}
i++;
}
I solved the problem, thanks for the help. I had to allocate memory for each line, otherwise my files vector always pointed to the same buffer. I just added the following line before atributingthe value of temp to files:
files[j] = (char*) malloc (size of (char) * strlen(temp);
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.