Coding & Programming/C, C++

[C/C++] 동적으로 파일 사이즈(크기) 구하고 메모리 할당 후 파일 읽기(dynamically get the file size, alloca

mainCodes 2021. 2. 28. 08:45

[C/C++] 동적으로 파일크기 구하고 메모리 할당 후 파일 읽기(dynamically get the file size, allocate memory and read the file : stat, calloc, free functions example)

 

안녕하세요 JollyTree입니다. 
컴퓨터에 저장되어 있는 파일의 크기는 다양합니다. 이런 다양한 크기의 파일을 읽어 메모리에 저장하기 위해서는 파일 크기보다 큰 크기의 버퍼를 할당하면 됩니다. 하지만, 프로그램 입장에서는 이를 예측하기는 어려우므로, stat 함수를 이용하여 읽으려는 파일의 크기를 구한 후 파일 크기에 맞는 크기의 메모리를 동적으로 할당하면 불필요하게 낭비되는 메모리를 최소화 할 수 있게 됩니다. 또한 stat 함수는 파일 크기(total size) 외 device id, user id, group id 등의 상태 정보를 struct stat 구조체로 반환합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    struct stat
    {
        _dev_t         st_dev;         //device id
        _ino_t         st_ino;        //inode number 
        unsigned short st_mode;     //protection
        short          st_nlink;    //number of hard links
        short          st_uid;      //user ID of owner
        short          st_gid;        //group ID of owner
        _dev_t         st_rdev;        //device ID
        _off_t         st_size;        //total size
        time_t         st_atime;    //time of last access
        time_t         st_mtime;    //time of last modification
        time_t         st_ctime;    //time of last status change
   };
 

예제 코드를 보시면 더 쉽게 이해 하실 수 있습니다.
* 참고 : 본 예제 코드는 Visual Studio 2019 환경에서 작성되었습니다.

예제(Example)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma warning(disable: 4996)
#define _CRT_SECURE_NO_WARNINGS 1
 
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>   
#include <fcntl.h> 
#include <io.h>
#include <stdlib.h>
 
int main()
{
    char filename[256= "codes.txt";
    int fd;
    int filesize, readlen;
    struct stat st;
    char* buf;
 
 
    if (access(filename, 0!= 0)
    {
        printf("'%s' does not exist!", filename);
        return 1;
    }
 
    if ((fd = open(filename, (_O_RDONLY | _O_TEXT))) == -1)
    {
        printf("open error '%s'", filename);
        return 1;
    }
 
    if (stat(filename, &st) < 0) //파일 상태정보 구하기
    {
        printf("stat error '%s'", filename);
        return 1;
    }
    filesize = st.st_size; //파일 전체 크기 정보

//파일 크기+1 만큼 동적으로 메모리를 할당
    if ((buf = (char*)calloc(1, filesize + 1)) == NULL)
    {
        printf("can't calloc '%d' bytes", filesize + 1);
    }
    buf[filesize] = 0;

//할당한 메모리로 파일 읽기
    if ((readlen = read(fd, buf, filesize)) < filesize)
    {
        close(fd);
        printf("read error %d,[%d]", filesize, readlen);
        return 1;
    }
    close(fd);
 
    printf("[실행결과]\ncodes.txt 파일 크기 = %d\n", filesize);
    printf("codes.txt 파일 내용 = %s\n", buf);

//메모리 해제
    free(buf);
        
    return 0;
}
 


실행결과