开发者

Trying to scan lines of a file into a ragged array (array of pointers) in C

开发者 https://www.devze.com 2023-03-06 15:12 出处:网络
running UNIX through putty, and using vi and gcc. I am attempting to read in a line of a file and using a ragged array store the lines.

running UNIX through putty, and using vi and gcc. I am attempting to read in a line of a file and using a ragged array store the lines. I won't provide the whole code because it is unnecessary,

main(){
   char func[51];
   char * functions[201];
   FILE * inf;
   if (( inf = fopen("test.txt", "r")) == NULL){
       printf("can't open so exiting\n");
       exit(EXIT_SUCCESS)


   int i;
   i = 0;
   while( fscanf(inf, "%s", func) != EOF){
        functions[i] = func;
        i++;
   }
   printf("%s\n", *functions); /* this is just for me to check if its working*/

  开发者_StackOverflow }

incldues stdio.h, stdlib.h and string.h

SO the code works in that it runs through the file and during the while loop it stores the line but I want it so that functions[0] stores a pointer leading to the first line and functions[1] stores a pointer leading to the second line and so on. I'm not sure how to do this, any help would be appreciated thanks :)


You need to assign a copy of func to functions[i], as in functions[i] = strdup(func), if you have strdup.


Your problem is that you are reusing the func array - all functions[i] point to the same place and therefore will contain the same string (the last one you read). You will need to allocate enough memory for all your different strings.

Have a look at this similar question.


Please fix your formating / code blocks now it seems like you are reading test.txt when you have failed to open the file and exited the program.

You have to keep in mind that the variable func points to the data structure func[51] now when you fscanf you overwrite func[51] all the time with a new line. And since your are storing the address pointing to func[51] to in the array functions you don't actually store the contents of the char array (func[51]).

You could solve this by make your functions array an two-dimensional array char functions[201][51] and then use a strcpy to copy the data structure func is pointing to to functions[i] with strcpy(functions[i], func);

this will result in something like:

main() {
    char func[51];
    char functions[201][51];
    FILE * inf;
    if (( inf = fopen("test.txt", "r")) == NULL) {
        printf("can't open so exiting\n");
        exit(EXIT_SUCCESS)
    } // <-- you are missing this one

    int i = 0;
    while( fscanf(inf, "%s", func) != EOF){
        strcpy(functions[i++], func);
    }
    printf("%s\n", *functions); /* this is just for me to check if its working*/
}

This could also be:

while (fscanf(inf, "%s", functions[i++]) != EOF);
0

精彩评论

暂无评论...
验证码 换一张
取 消