mikan's technical note

仕事&趣味で実験した小技の備忘録です(Linux,windows,DOS等)

MENU

【C言語】改行コードCRLF(0x0d0a)形式ファイルを、改行コードLF(0x0a)形式ファイルに変換

//
// 【改行コード CRLF(0x0d0a) -> LF(0x0a)】※Windows7で動作確認済
// (c) 2017 mikan
// ※使用にあたっては利用者の自己責任でお願いします。
//
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>

// 【方法1】ファイルを、CRLF -> LF 変換
int CRLFtoLF1(char *in, char *out)
{
    int     i,j;
    int     fd1, fd2;
    int     size, readsize, writesize;
    int     rts;
    char    work1[4096];
    char    work2[4096];

    fd1 = open(in, O_BINARY | O_RDONLY);
    if(fd1 == -1) {
        perror("open()");
    }
    fd2 = open(out, O_BINARY | O_CREAT | O_RDWR | O_TRUNC, S_IREAD | S_IWRITE);
    if(fd2 == -1) {
        perror("open()");
        close(fd1);
        return -1;
    }

    writesize = 0;
    memset(work1, 0x00, sizeof(work1));
    memset(work2, 0x00, sizeof(work2));
    readsize = read(fd1, work1, sizeof(work1));
    if(readsize == -1) {
        perror("read()");
        close(fd2);
        close(fd1);
        return -1;
    }
    
    for(i = 0, j = 0; i < readsize; i ++) {
        if(work1[i] == 0x0d && work1[i+1] == 0x0a) {
            i ++;
        }
        work2[j] = work1[i];
        j ++;
        writesize ++;
    }

    size = write(fd2, work2, writesize);
    if(size == -1) {
        perror("write()");
        rts = -1;
    } else {
        rts = 0;
    }

    close(fd2);
    close(fd1);

    return rts;
}

// 【方法2】ファイルを、CRLF -> LF 変換
int CRLFtoLF2(char *in, char *out)
{
    int     size;
    int     rts;
    FILE    *fp1, *fp2;
    char    work1[4096];

    rts = 0;

    fp1 = fopen(in, "r");
    if(fp1 == NULL) {
        perror("fopen()");
    }
    fp2 = fopen(out, "wb");
    if(fp2 == NULL) {
        perror("fopen()");
        fclose(fp1);
    }

    memset(work1, 0x00, sizeof(work1));

    while(1) {
        if(fgets(work1, sizeof(work1), fp1) == NULL) {
            break;
        }
        size = fprintf(fp2, "%s", work1);
        if(size < 0) {
            perror("fprintf()");
            rts = -1;
        }
    }

    fclose(fp2);
    fclose(fp1);

    return rts;
}

int main(int argc, char* argv[])
{
    // どちらも結果は同じです

    // 変換1
    CRLFtoLF1("c:\\work\\in.txt", "c:\\work\\out1.txt");

    // 変換2
    CRLFtoLF2("c:\\work\\in.txt", "c:\\work\\out2.txt");

    return 0;
}