본문 바로가기

C_study

[C] 코딩도장 71 : 파일에서 문자열을 읽고 쓰기

71.9 심사문제: 파일 크기만큼 파일 읽기

#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); // 문자열은 끝에 NULL값이 들어가야하므로 문자열의 크기보다 +1 해줍니다
    memset(buffer, 0, size+1);
    fseek(fp, offset, SEEK_SET); // offset으로 넘겨받은 값만큼 시작점에서 이동합니다
    *count = fread(buffer,sizeof(char),size,fp); // count를 역참조하여 읽은 횟수를 함수 밖으로 넘겨줍니다

    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;
}

71.10 심사문제: 파일을 부분적으로 읽기

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

int main()
{
    char *buffer;
    int size;
    FILE *fp = fopen("words.txt", "r");
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    buffer = malloc(size);
    
    fseek(fp, 7, SEEK_SET);
    fread(buffer, 4, 1, fp);
    printf("%s", buffer);
    
    memset(buffer, 0, 10);
    
    fseek(fp, -6, SEEK_END);
    fread(buffer, 2, 1, fp);
    printf("%s", buffer);
    
    free(buffer);
    return 0;
}

71.11 심사문제: 파일을 읽은 뒤 거꾸로 저장하기

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

int main()
{
    char *buffer;
    int size;
    FILE *fp = fopen("words.txt", "r");
    
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
   
    buffer = malloc(size + 1);
    memset(buffer, 0, size+1);
    fread(buffer, size, 1, fp);
    
    for(int i = size-1 ; i >= 0 ; i--)
    {
        fwrite(&buffer[i], sizeof(char), 1, stdout);
    }
    
    free(buffer);
    return 0;
}