简体   繁体   中英

Reading Strings of unknown length from text file and printing them

I have a question on how to read strings of unknown length from a text file while printing them out when the program comes across a '\\n'. The program should end if it notices that the file has no more strings left to read.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEFLEN 2 
#define CHUNKSZ 2 


char *getStrFromFile(FILE *fpin); 

int main(void)
{
      FILE *fpin;
      fpin = fopen("test.txt","r");
      int d = 0;

while(1)
{
    char *ln;
    ln = getStrFromFile(fpin);
    if (!ln)
        break;
    ++d;
    printf("line %d : %s\n", d, ln);
    free(ln);
}
    fclose(fpin);
    return(0);
}



char *getStrFromFile(FILE *fpin) 
{

    int i = 0;
    char *line;


    line = (char*)malloc(DEFLEN);

    fgets(line,strlen(line),fpin);

        if(line[strlen(line-1)] == '\n')

            return line;

char  *temp;
temp = line;
char *read;

    read = (char*)malloc(CHUNKSZ);

    fgets(read,strlen(read),fpin);

    line = (char*)malloc(strlen(temp)+strlen(read));

    for(i; i<strlen(temp);i++);
        line[i]=temp[i];

    for(i;i<strlen(read);i++);
        line[i+strlen(temp)] = temp[i];

    free(read);
    free(temp);

    return line; 

}

The problem is that when I run the program it runs an infinite loop(which I suspect is the while(1) in the main), but doesn't appear to print out the strings in the text file.

What it prints is just:

line 1 :
line 2 :
line 3 :

... and so on till forever it seems.

When I need it to print, for example:

line 1 : 0
line 2 : 012345
line 3 :
line 4 : 567890

Example of the program reading a text file with 4 lines.

Quite frankly i'm stuck and don't know what im doing wrong. I've gotten it to print something, but its was something along the lines of the ASCII character 177 177 + 177 177.

Which seems to point to an error in this line of code:

line = (char*)malloc(strlen(temp)+strlen(read));

Only thing I can think of is that my return line; is incorrect? I am lost here help would be greatly appreciated!

There is a need to extend to buffer to reading. But your way is wrong.

char *getStrFromFile(FILE *fpin){
    int i=0, ch, size=DEFLEN+1;
    if(EOF==(ch=fgetc(fpin)))
        return NULL;
    ungetc(ch, fpin);
    char *line = malloc(size);

    while(EOF!=(ch=fgetc(fpin)) && ch != '\n'){//Do not include '\n'
        line[i++] = ch;
        if(i==size-1){
            size += CHUNKSZ;
            line = realloc(line, size);
        }
    }
    line[i] = '\0';
    return line;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM