安全读取长度未知的字符串 [英] Safely reading in strings of unknown length

查看:118
本文介绍了安全读取长度未知的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用fgets安全地获取未知长度的字符串

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);
    }
   }
}

我也收到DEFLEN = malloc行的错误

I also get an error for the DEFLEN = malloc line

错误:左值必须作为赋值的左操作数

error: lvalue required as left operand of assignment

推荐答案

预编译器将使用代码中的DEFINE.因此,您不能为定义分配任何内容!

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

此行

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

被替换为

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

这篇关于安全读取长度未知的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆