简体   繁体   English

使用fgets +动态内存分配

[英]Using fgets + dynamic memory allocation

I have a homework problem that I need help with. 我有一个家庭作业问题,需要帮助。 I need to implement a function char *getStrFromFile(FILE*); 我需要实现一个功能char *getStrFromFile(FILE*); . I just simply don't understand it. 我只是不明白。 I have attempted to figure out the question. 我试图找出问题所在。

This function safely reads a complete line of unknown length from the open file pointed to by fpin. 此函数从fpin指向的打开文件中安全地读取未知长度的完整行。 It returns a line that is at most CHUNKSZ-1 characters longer than the minimum needed to hold the line. 它返回的一行最多比保留该行所需的最小字符长CHUNKSZ-1个字符。 It initially allocates an array of DEFLEN characters to hold the string, and if this space is inadequate to hold the string, it will iteratively create a new string that is CHUNKSZ larger, copy the old string to it release the old string, and then read in more characters from the file, and continue this until the entire line of arbitrary length can be returned. 它最初分配一个DEFLEN字符数组来容纳该字符串,并且如果此空间不足以容纳该字符串,它将迭代创建一个更大的CHUNKSZ的新字符串,将旧字符串复制到其中以释放旧字符串,然后读取从文件中输入更多字符,然后继续执行此操作,直到可以返回整行的任意长度。

RETURNS: NULL if no characters are left in fpin, otherwise: pointer to allocated array at most CHUNKSZ-1 characters longer than miminum necessary to hold an arbitrarily long line from file fpin 返回值:如果fpin中没有剩余字符,则为NULL,否则:指向分配的数组的指针最多CHUNKSZ-1个字符,其长度比保留文件fpin中任意长的行所必需的最小值

 int main(int nargs, char *args[])
 {
    FILE *fpin;
    char *getStrFromFile(FILE*);
    if (nargs != 2)
    {
       fprintf(stderr, "USAGE: %s <file>\n", args[0]);
       exit(1);
    }
    fpin = fopen(args[1], "r");
    while(1)
    {
       char *ln;
       ln = getStrFromFile(fpin);
       if (!ln)
          break;
       printf("%s", ln);
       free(ln);
    }
    fclose(fpin);
    return(0);
 }

That is the main method I have to use. 那是我必须使用的主要方法。 Here is what I know so far. 到目前为止,这是我所知道的。

char *getStrFromFile(FILE *fpin)
{
  char string[DEFLEN];
  if(fgets(string, CHUNKSZ, fpin) != NULL) {
    int l = lstr(string);
    if(string[l-1] = '\n') {
      return string;
    } else {
      int size = 1;
      int end = 0;
      while (string[l-1] != '\n') {
        size += CHUNSZ;
        char *s2 = (char*)malloc(sizeof(char)+size);
        for(i = 0+end; i < lstr(string); i++) {
          s2[i] = string[i];
        }
        end += lstr(string);
        fgets(string, size + end, fpin);
        return s2;

This is not correct. 这是不正确的。

if(string[l-1] = '\n')

it must be 一定是

if(string[l-1] == '\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM