상세 컨텐츠

본문 제목

[c언어] 코딩도장 71.9 파일 크기만큼 파일 읽기 문제풀이

c언어

by ~지우~ 2021. 7. 21. 20:48

본문

728x90

오늘은 코딩도장 71.9 심사문제 풀이를 해보겠습니다.

 

fseek(파일 포인터, 이동할 거리, 이동 방식)

fread(저장할 문자열 포인터, 문자열 크기, 반복 횟수, 파일 포인터) ->이때 문자열 크기를 sizeof(char)로 지정하면 문자열 길이를 반환한다.  

 

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getFileSize(FILE* fp)
{
    int size;
    int currPos = ftell(fp);

    fseek(fp, 0, SEEK_END);
    size = ftell(fp);

    fseek(fp, currPos, SEEK_SET);

    return size;
}

char* getData(int offset, int size, int* count, FILE* fp)
{
    char* buffer = malloc(size + 1);
    memset(buffer, 0, size + 1);
    fseek(fp, offset, SEEK_SET);
    *count = fread(buffer, sizeof(char), size, fp);

    return buffer;
}

int main()
{
    char* buffer;
    int size;
    int count;

    FILE* fp = fopen("words.txt", "r");

    size = getFileSize(fp);
    buffer = getData(0, size, &count, fp);

    printf("%s\n", buffer);
    printf("%d", count);

    fclose(fp);

    free(buffer);

    return 0;
}
728x90

관련글 더보기

댓글 영역