Safe reading in rows of unknown length

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

This is the code that I have been able to find so far, but now I'm stuck with how to move 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 string DEFLEN = malloc

error: lvalue required as left assignment operand

0
source share
2 answers

DEFINE in your code is used by the precompiler. Therefore, you cannot assign anything to determine!

This line

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

replaced by

 4 = malloc( CHUNKSZ *sizeof(int)); 
+1
source

You cannot reappoint DEFLEN . This is a placeholder that is replaced before compilation, and its existence outside the replaced value disappears at runtime.

0
source

Source: https://habr.com/ru/post/979207/


All Articles