用fopen打开文件,c \ ubuntu

时间:2015-05-16 19:18:37

标签: c eclipse ubuntu fopen

我试图用fopen打开文件,并为" huffman tree"读取\ write。 在我完成了对文本的阅读之后,我尝试在另一个文件中写一个"字典"那说每个字母的代码是什么。 我有一个恐怖,我发现了类似的东西,除了原因是旧版的日食,但它不是普罗兰。 我正在使用ubuntu中的eclipse进行c编程。

主要看起来像:

int main(){
    FILE *fsrc;
    node *root;
    if( (fsrc  = fopen( "src.txt", "r" )) == NULL ){ //
        printf( "The file 'src.txt' was not opened\n" );
        return 0;
    }
    else {
        printf( "The file 'src.txt' was opened\n" );
    }
    root = getBinTree(fsrc);
    printTree(&(*root));
    huffman(root); 
    return 0;
}

这是写入目标文本的功能

void printhtree(node *n,FILE *trg){
       char *str = calloc(1, sizeof(char));
       node *ptr=n;
       while (!(ptr->m_hls && ptr->m_hrs)){
           while(ptr->m_hls){
               n=ptr;
               ptr = ptr->m_hls;
               str = realloc(1,sizeof(char)*(strlength(str)+1));
               *(str+strlength(str)-1)='0';
           }//while
           if(!(ptr->m_hrs)){
               printf("%s-%c ",str,ptr->m_ch);
               n->m_hls = NULL;
               return;
           }//if
           while(ptr->m_hrs){
               n=ptr;
               ptr = ptr->m_hrs;
               str = realloc(1,sizeof(char)*(strlength(str)+1));
               *(str+strlength(str)-1)='1';
           }//while
       }//while
       if (!(ptr->m_ch)){
           fputc(ptr->m_ch,trg);
           fputc(' ',trg);
           fputs(str,trg);

           n->m_hls = NULL;
           return;
       }//if
   }//printhtree

这是激活&pringhtree"功能:

  ‪void drawTree(node *n,FILE *trg‬‬){
        while(!(n))
           printhtree(n,trg);
   }

错误在第一行绘制树上: " void drawTree(node * n,FILE * trg)" 它说: "此行的多个标记 遇到错误的字符序列 流浪' \ 252'在程序中,与数字254,342,200相同。

也有同样的错误,我在程序开头写了所有函数的名称。

非常感谢

1 个答案:

答案 0 :(得分:2)

这是您的代码中的一个重要问题

str = realloc(1,sizeof(char)*(strlength(str)+1));

出于多种原因

  1. 语法错误,因为你是realloc()地址0x01
  2. 您不应该立即覆盖指针,因为如果发生错误,那么您将无法恢复,realloc()的良好用法就像

    void *tmp = realloc(str, 1 + strlength(str));
    if (tmp != NULL)
        str = tmp;
    
  3. 这没有错,但它会使您的代码变得不必要,sizeof(char)保证为1

  4. 大概strlength()模仿strlen(),因此您不想计算两次长度,存储它并使用该值。

  5. 您首次使用malloc()分配空间,但由于代码中误用realloc()而完全丢弃该指针,而且您并不真正需要分配空间除了在写入指向数据之前,您可以将realloc()替换为malloc()并删除calloc(),这样就不必要地将所有值初始化为0,不需要那个。

  6. 您只初始化设置为str的{​​{1}}的最后一个值,但其余数据仍然未初始化,因为实际分配内存的函数将是{{1如果它被正确使用,特别是因为'\0'正在分配一个字节。