您的位置:首页 > 编程语言 > C语言/C++

计通网实验的准备工作(C语言实现)

2014-04-03 13:51 399 查看
今天老师布置计通网实验的项目。要实现两台计算机之间的通信。现在先考虑编码问题:即,如何实现中文和英文的混合编码。

经过实验,C语言中,一个中文字符的长度是2,但是英文字符的长度是1.如果加以区分,是一件十分困难的事情。但是,在文件的输入中,读入两个char类型,分别对应中文的前一字节和后一字节,则在输出时可以正常输出为一个中文字符(需连续输出)。于是,我的想法是:不用考虑中文还是英文,只用char类型的操作,将所有的信息传递过去,然后两端使用同一种编码方式,就可以读出同样的内容了。

于是,现在所有的难点就在于和二进制之间的转换了。因为实验二进制是使用表示的,所以现在的将二进制编码以文本文件的方式保存。code程序用于将消息翻译为二进制,decode程序用于将二进制翻译为消息。

源程序如下:

// code.c
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

int getFileLength(FILE *fp);
void setBinarySequence(short binarySequence[], char set, int loc);

int main(void)
{
	FILE *sendFile, *out;
	char c;
	wchar_t wc;
	short* binarySequence;
	int i = 0;
	int fileLength;

	if((sendFile = fopen("send.txt", "r")) == NULL)
	{
		fprintf(stderr, "Can't open file: send.txt\n");
		exit(EXIT_FAILURE);
	}

	fileLength = getFileLength(sendFile) + 1;
	binarySequence = (short *)malloc(sizeof(short) * sizeof(char) * 8 * fileLength);
	while((c = getc(sendFile)) != EOF)
	{
		setBinarySequence(binarySequence, c, i);
		i++;
	}
	setBinarySequence(binarySequence, c, i);

	fclose(sendFile);

	if ((out = fopen("out.txt", "w")) == NULL)
	{
		fprintf(stderr, "Can't open file: out.txt");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < fileLength * 8; i++)
	{
		fprintf(out, "%d", binarySequence[i]);
	}

	printf("输出:out.txt已在当前目录下生成。\n");
	fclose(out);
	free(binarySequence);

	return 0;
}

int getFileLength(FILE *fp)
{
	int length;
	if (fp == NULL)
		return -1;
	fseek(fp, 0L, SEEK_END);
	length = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	return length;
}

void setBinarySequence(short binarySequence[], char set, int loc)
{
	int i;
	for (i = 0; i < 8; i++)
	{
		if (set & (1 << i))
			binarySequence[loc * 8 + i] = 1;
		else
			binarySequence[loc * 8 + i] = 0;
	}
}


code.c:

// decode.c
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "CRC.h"

char readBinarySequence(FILE *fp);

int main()
{
	FILE *getFrom, *get;
	char c;
	char* info;
	int len;
	int i = 0;

	if ((getFrom = fopen("get.txt", "r")) == NULL)
	{
		fprintf(stderr, "Can't open file: get.txt\n");
		exit(EXIT_FAILURE);
	}
	len = (getFileLength(getFrom) - 1) / 8;
	info = (char*)malloc(sizeof(char) * len);
	
	printf("得到的消息是:\n");
	while ((c = readBinarySequence(getFrom)) != EOF)
	{
		printf("%c", c);
		info[i++] = c;
	}
	info[i] = EOF;

	fclose(getFrom);

	if ((get = fopen("get.txt", "w")) == NULL)
	{
		fprintf(stderr, "Can't open file: get.txt\n");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < len; i++)
		fprintf(get, "%c", info[i]);

	printf("\n\n消息已经保存在当前目录下的get.txt.\n");
	fclose(getFrom);
	fclose(get);

	return 0;
}

char readBinarySequence(FILE *fp)
{
	int i;
	char bit;
	char c = 0;
	for (i = 0; i < 8; i++)
	{
		bit = getc(fp);
		if (bit == '1')
			c |= (1 << i);
		else if(bit != '0')
		{
			fprintf(stderr, "Illegal character!\n");
			exit(EXIT_FAILURE);
		}
	}

	return c;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: