将.txt文件中的行存储在变量中

时间:2018-08-28 09:30:35

标签: c

目前,我的代码仅存储.txt文件的最后一行。我将如何将所有行存储到变量中以便以后访问?谢谢

int main() {
    FILE *ptr_fp;
    char Line[600];

    ptr_fp = fopen("messages.txt","r");

    if(ptr_fp != NULL){
        while(fgets(Line,600,ptr_fp)){
            printf("%s",Line);
        }
        printf("\n");
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

如何将Line分配给二维数组,然后稍后可以访问这些行。这是示例代码

int main() {
    FILE *ptr_fp;
    char Line[600][600];

    ptr_fp = fopen("messages.txt","r");
    int i = 0;
    if (ptr_fp != NULL){
        while(fgets(Line[i],600,ptr_fp )&& i <600){
            i++;
        }
    }
    for (int j = 0; j < i; j++){
        printf("%s",Line[j]);
    }
    return 0;
}

答案 1 :(得分:0)

int main() {
FILE *ptr_fp;
char **Line_buf,*buf; //declaring double pointer to store lines from file
int line = 0 , biggest_line_size = 0;//To store number of lines in file 
ptr_fp = fopen("messages.txt","r");
int i = 0,file_size=0;
lseek(ptr_fp,0,SEEK_END); // file ptr moving at last .
file_size=ftell(ptr_fp);
buf=malloc(file_size); // allocating memory dynamically to buffer
rewind(ptr_fp);           //resetting file ptr to initial position .
if (ptr_fp != NULL)
{
    while(fgets(buf,file_size,ptr_fp ))
   {
        line++;//counting number of lines
        if(strlen(buf)>biggest_line_size)
         biggest_line_size=strlen(buf); // finding biggest line in file
    }
 }
 rewind(ptr_fp);

 //allocating dynamic memory to 2D array buffer.
 line_buf = malloc(size(char*)*line);
  for(i=0;i<line;i++)
 line_buf[i]=malloc(biggest_line_size);

// fetching the line by line into buffer from file
for ( i = 0; i < line; i++){
    fgets(line_buf[i],biggest_line_size,ptr_fp);

//printing line by line
for(i=0;i<line;i++)
printf("%s",line_buf[i]);

// de-allocating the 2D array
for(i=0;i<line;i++)
free(line_buf[i]);

free(line_buf);
return 0;

}