Using fgets to copy lines into string array?

后端 未结 2 939
说谎
说谎 2021-01-28 02:52

I\'ve got a C program that I\'m trying to write which intends to reverse the lines of a file. I am still very inept at C (though I come from a Java background), so I am very lik

2条回答
  •  爱一瞬间的悲伤
    2021-01-28 03:21

    In you code you are making each index of str array to point to same array buffer. Thats is why you are getting same value (value in buffer) for evey index in str array. You can use code using array like this

    #define MAX_LINES 100
    #define MAX_CHAR 80
    
    int main(int argc, char *argv[])
    {
            if(argc != 2)
                     goto out;
             FILE *fp;
             char str[MAX_LINES][MAX_CHAR];
             char buffer[MAX_CHAR];
             char *revstr[MAX_CHAR];
             int curr_line = 0, i = 0, j =0;
    
             fp = fopen(argv[1],"r");
    
             out:
             if (fp == NULL && argc != 2){
                     printf("File cannot be found or read failed.\n");
                     return -1;
             }
    
             /* printf("This part of the program reverses the input text file, up to a  maximum of 100 lines and 80 characters per line.\n The reversed file, from the last (or    100th) line to the first, is the following:\n\n"); */
    
             /* fgets reads one line at a time, until 80 chars, EOL or EOF */
             while(curr_line < MAX_LINES && ((fgets(buffer, MAX_CHAR, fp)) != NULL)){
    
                     //str[i] = buffer;
                     memcpy(str[i], buffer, strlen(buffer));
                     curr_line++;
                     ++j;
                     ++i;
             }
    
             for(i = 0; i < 4; ++i) 
                     printf("%s \n", str[i]);
    
    
             printf("END OF PROGRAM RUN.");
             return 0;
     }
    

    Also you are not modifying variable currn_line

提交回复
热议问题