Click here to Skip to main content
15,893,663 members

How to input a file for Huffman coding(using C language)

Member 9954636 asked:

Open original thread
Hi,

I have written a Huffman C program that encodes and decodes a hardcoded input. Now I want to have the program accept text from an INPUT FILE instead of having hardcoded text in the file, which will then be passed to the encode function in main and then decoded, after the my huffman tree and frequencies are built.

I have searched the last 4 hours looking at examples and trying but Xcode(IDE) gives error can never locate the file or gives me (lldb) error when it executes the fgets function. I must say it is very frustrating, but I want to solve it.

An example or solution would be nice.

Here is the current code I have that accepts the hardcoded text that works and the output. The huffmanpq.h is where I put the huffman and priority queue data structures being used.

Thank you for any help!
C++
#include <stdio.h>
#include <string.h>
#include "huffmanpq.h"

int main(void)

{
	int i;
	char *str = "Hello Code Project", buf[1024];  //given text to be encoded
	init(str); //creating huffman tree
	
	printf("The Huffman tree is frequency table is created.\n");
	for (i = 0; i < 128; i++)
		if (code[i]) printf("'%c': %s\n", i, code[i]); //display the huffman tree
    
	encode(str, buf);
	printf("\nEncoded text: %s\n", buf);
	printf("\n");
	printf("Decoded text: ");
	decode(buf, q[1]);
    
	return 0;
}

output:
The Huffman tree is created.
HTML
' ': 011
'C': 10110
'H': 0000
'P': 10111
'c': 0011
'd': 0001
'e': 100
'j': 0010
'l': 110
'o': 111
'r': 010
't': 1010

Encoded text:
HTML
000010011011011101110110111000110001110111010111001010000111010

Decoded text:
HTML
Hello Code Project
Tags: C

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900