Safely reading in strings of unknown length

2019-09-17 08:26发布

问题:

I am trying to safely get in strings of unknown length with using fgets

This is the code I have been able to come up with so far, but now I am stuck on how to conitinue forward.

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

#define DEFLEN 4 
#define CHUNKSZ 2 


int i = 0;
int size =0;
int size2 =0;
char* ln1;
char* ln2;
FILE *fpin;
char *getStrFromFile( FILE *fpins  )/*file stream to read string from */
 {

 DEFLEN = malloc( CHUNKSZ *sizeof(int));
 while(1){
  if( fgets(ln1+size2, DEFLEN, fpin) == NULL) {
    if(size > 0){
     return (ln1);
    }
    else {
      return (NULL);
      free(ln1);
    }
  }
 else{
   size2=strlen(ln1);
   if(ln1[size2 -1] == '\n'){
     return (ln1);
   }
    else{
     ln2=malloc(size+CHUNKSZ * sizeof(char));
     assert(ln2);
     strcpy(ln2, ln1);
     free (ln1);
     ln1 = ln2;
     return (ln1);
    }
   }
}

I also get an error for the DEFLEN = malloc line

error: lvalue required as left operand of assignment

回答1:

A DEFINE in your code is used by the pre-compiler. So you cant assign anything to a define!

This line

DEFLEN = malloc( CHUNKSZ *sizeof(int));

is beeing replaced by

4 = malloc( CHUNKSZ *sizeof(int));


回答2:

You can't re-assign DEFLEN. It's a placeholder that is replaced before compilation, and its existence beyond the replaced value is gone at runtime.



标签: c malloc fgets