C_C++

(C언어) uniq: 중복 라인을 제거하는 소스

고니자니 2023. 3. 28. 15:04
반응형

파일 내용에서 똑 같은 행이 2개 이상 연달아 있으면 중복된 라인을 제거해서 한 개씩만 표준 출력하는 C언어 프로그램입니다.

 

테스트로 사용한 uniq.txt 파일은 다음과 같습니다.

Get
Get
a string
from
a stream.
a stream.
a stream.
Get a string from a stream.

 

실행된 결과는 다음과 같습니다.

중복된 행 제거

 

C언어 코드

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio
#include <stdio.h>
#include <string.h>
#define TRUE	1
#define FALSE	0
#define LEN		200
#define swap(a,b)	{ char *temp; temp=a; a=b; b=temp; }

int main()
{
	char buffer1[LEN] = { 0 };
	char buffer2[LEN] = { 0 };;
	char* base, * new;
	FILE* fp;

	base = buffer1;
	new = buffer2;

	if ((fp = fopen("uniq.txt", "rt")) == NULL)
	{
		printf("파일 읽기 오류\n");
		return -1;
	}

	if (fgets(base, LEN, fp))
		printf("%s", base);
	while (fgets(new, LEN, fp))
	{
		if (strcmp(new, base))
		{
			printf("%s", new);
			swap(base, new);
		}
	}

	fclose(fp);

	return 0;
}

 

 

728x90
반응형