공부,일/c언어

저수준 파일 입출력

fromnothing1 2021. 6. 29. 09:06

터보 c 환경에서 컴파일 

1 . create

#include<fcntl.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <io.h>
#include <stdlib.h>
#include<stdio.h>

int main()
{
    int  outhndl;
    if ((outhndl =
        open("data.dat", O_CREAT | O_EXCL, S_IREAD | S_IWRITE)) == -1) 
    {
        perror("Can't open file for output");
        exit(1);
    }
    else
    {
        printf("success to create file\n");
    }

    close(outhndl);
    getch();
    return 0;
    
}

 

2. read

#include <stdio.h>
#include <io.h>
#include <fcntl.h>



int main()
{
	int iFileNum;
	int iRet;
	char* a;
	iFileNum = open("test.txt", O_RDONLY | O_BINARY);
	if (-1 == iFileNum)
	{
		printf("can't open file.");
		return 0;
	}
	else
	{
		printf("open file.\n");
	}
	iRet = read(iFileNum, a, 1); // 읽은 파일 byte 수 출력
	printf("iRet : %d\n", iRet);
	printf("a : %c\n", *a);

	getch();
	return 0;
}

 

3. write

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#pragma warning(disable : 4996)// 보안 문제로 뜨는 경고 메세지 무시 


int main()
{
	int iFileNum;
	int iRet;
	char a = 'b';
	char b = 'b';
	iFileNum = open("test.txt", O_WRONLY|O_BINARY|O_TRUNC); 
	if (-1 == iFileNum)
	{
		printf("can't open file.");
		return 0;
	}
	else
	{
		printf("open file.\n");
	}
	iRet = write(iFileNum, &a, 1); // 읽은 파일 byte 수 출력
	if (iRet == -1)
	{
		printf("can't write");
	}
	else
	{
		printf("can write");
	}

	close(iFileNum);
	getch();
	return 0;
}