Safely reading in strings of unknown length

牧云@^-^@ 提交于 2020-01-06 14:58:09

问题


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.



来源:https://stackoverflow.com/questions/19507995/safely-reading-in-strings-of-unknown-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!