본문 바로가기
: ) 파일처리

[C언어_파일처리] 랜덤읽기 (레코드 랜덤 읽기)

by miiinn 2022. 4. 12.

OS : Linux 우분투 버전 18.04

컴파일러 : gcc 7.5

 

 

<명세>

주어진 <record_file_name> 파일에 저장되어 있는 모든 레코드를 랜덤(random)하게 하나씩 사용자 프로그램 상으로 읽어 들이며, 이 과정에서 발생하는 전체 시간 비용을 출력한다. 아래 예시와 같이, 명령의 실행 후 화면에 그 시간 비용을 usec 단위의 정수값으로 출력한다.
 
a.out <record_file_name>
 
<예시>
$ a.out student.dat
120300 usec

 

 

 

<소스 코드> - rand_read.c

#include <stdio.h>
#include <sys/types.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>

//#define SUFFLE_NUM	10000	// 이 값은 마음대로 수정 가능

void GenRecordSequence(int *list, int n);
void swap(int *a, int *b);
// 필요한 함수가 있으면 더 추가할 수 있음

int main(int argc, char **argv)
{
    struct timeval start, end;

    gettimeofday(&start, NULL);

    FILE *fp = fopen(*(argv+1), "r");
    
    // 파일 크기
    fseek(fp, 0, SEEK_END);
    int size = ftell(fp);

    fseek(fp, 0, SEEK_SET);

    
    int *read_order_list = (int *)malloc(sizeof(int *)*(size/200)); // 레코드 개수 만큼 메모리할당

    int num_of_records = size / 200; // 파일의 크기


	// 이 함수를 실행하면 'read_order_list' 배열에 읽어야 할 레코드 번호들이 순서대로
	// 나열되어 저장됨. 'num_of_records'는 레코드 파일에 저장되어 있는 전체 레코드의 수를 의미함.

    GenRecordSequence(read_order_list, num_of_records); 

/*
   // 리스트 값 확인
    for(int i=0; i<num_of_records; i++){
        printf("list[%d] : %d\n",i,*(read_order_list+i) );
    }
    
  */  
    char buffer[200]; // 레코드 읽어올 버퍼

    // list 0번째 레코드이면 0~199 읽기  1번째 레코드면 200~399읽기 2번째면 400~599..
    for (int i=0; i<num_of_records; i++){
        fseek(fp, (*(read_order_list+i))*200 , SEEK_SET); // 해당 레코드 시작 위치로 옮기기
        fread(buffer, sizeof(char), sizeof(buffer), fp); // 200바이트씩 읽기
        memset(buffer, 0, sizeof(buffer)); 
    }

    fclose(fp);

    gettimeofday(&end, NULL);
    int time = ( (end.tv_sec + end.tv_usec) - (start.tv_sec + start.tv_usec) );
    printf("%d usec\n", time);

	// 'read_order_list'를 이용하여 레코드 파일로부터 전체 레코드를 random 하게 읽어들이고,
	// 이때 걸리는 시간을 측정하는 코드 구현


	return 0;
}

void GenRecordSequence(int *list, int n)
{
	int i, j, k;
    
	srand((unsigned int)time(0));

	for(i=0; i<n; i++)
	{
		list[i] = i;
	}
	
	for(i=0; i<n; i++)
	{
		j = rand() % n;
		k = rand() % n;
		swap(&list[j], &list[k]);
	}

	return;
}

void swap(int *a, int *b)
{
	int tmp;

	tmp = *a;
	*a = *b;
	*b = tmp;

	return;
}