File reading with variable length

1

I have a file with variable length (lines of variable length) and it has blank spaces. I want to read line by line to process it, but I can not detect the end of line.

I read the file with this instruction:

while (fscanf(fp,"%[^
while (fscanf(fp,"%[^%pre%]s",&reg_Lectura) != EOF)
]s",&reg_Lectura) != EOF)

What can I do? It is in C

    
asked by Leticia Hernandez Yescas 07.04.2018 в 05:35
source

1 answer

1

If you're only going to work on GNU systems (linux), you can use getline

char* line = NULL;
size_t len = 0;
ssize_t read = getline(&line, &len, fp)) != -1);

if( read != 0 )
{
  // ...
}

free(line);

If this is not the case, you can read character character and resize the buffer on the fly:

char* readLine(FILE* fp)
{
  size_t max_size = 100;
  char* line = (char*)malloc(max_size *sizeof(char)); // Reserva inicial para 99 caracteres

  size_t index = 0;

  while(1)
  {
    char c = getc(fp);
    if( c == EOF || c == '\n' )
      break;

    line[index] = c;
    ++index;
    if( index == max_line )
      line = (char*)realloc(line,max_line+100);
  }

  line[index] ='
char* line = NULL;
size_t len = 0;
ssize_t read = getline(&line, &len, fp)) != -1);

if( read != 0 )
{
  // ...
}

free(line);
'; // Finalizamos la cadena return line; }
    
answered by 11.04.2018 в 16:11