简体   繁体   中英

c- read in line from file

I am new to c, but I would like to read in text from a file. I don't know the length of the first line of the file, so how can I write the correct parameters for the fgets function? Right now I have:

char read[30]; // but I really don't know how long the line will be

while(fgets(read, sizeof(read), fp).......

You'll have to just keep reallocating and appending to a buffer until you reach the end of the line. The code isn't pretty, but there isn't a simple alternative using the standard C library:

char read[30];
char *line;
int len, total;

line = NULL;
total = 0;

do {
  if (fgets(read, sizeof(read), fp) == NULL)
    break;

  len = strlen(read);

  if (total == 0) {
    total = len;
    line = (char *)malloc(len);
    strcpy(line, read);
  } else {
    total += len;
    line = (char *)realloc(line, total);
    strcat(line, read);
  }
} while (read[len - 1] != '\n');

您必须为线路设置一个安全的合理最大长度并使用它。

Using the C standard library you will just have to accept some maximum line size there and go with it. If you detect that read does not end in a newline you could read more and append the additional data until you find the end of a line. However, for most applications where fgets() is acceptable for parsing, a fixed line length is also acceptable.

There's an off by one in your fgets(). If your buffer has a size of 30, you need to use sizeof(read)+1. Like Felice said, you'll need to set a safe maximum.

You have (at least) two choices. By far the most common is to allocate a buffer assumed to be "big enough" (eg, a couple of kilobytes) and just go with it (and quite possibly mis-behave if provided with data that doesn't fit that limitation).

The primary alternative is to allocate the memory for the buffer dynamically, and when/if that data you read doesn't fit, use realloc to increase the buffer size and read some more.

If you don't know your max. linesize you can read char by char and use realloc, then it's easy:

char *read = calloc(1,1),c;

while( c=fgetc(fp), !feof(fp) )
  if( c=='\n' )
  {
    puts(read);
    *read=0;
  }
  else
  {
    read = realloc(read,strlen(read)+2);
    read[strlen(read)+1]=0;
    strncat(read,&c,1);
  }
fclose(fp);
if( *read )
  puts(read);
free(read);

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