基本文件操作 - Create and write
- 基本文件操作函数
- open()
- read()
- write()
- close()
- Iseek()
代码块
代码块语法遵循标准markdown代码,例如:
- create and write file Test_10_2a.c
#include<stdio.h>
#include<errno.h>
#include<io.h>
#include<fcntl.h>
#include<string.h>
#define MAX_STRING_LENGTH 3
#define FILENAME "test.bin"
int WriteData(int fh, void* buf, int len);
struct data {
int i;
float f;
char string[MAX_STRING_LENGTH+1];
char end[4];
};
int main(){
struct data block;
int fh, rtn;
memset(&block,0,sizeof(block));
block.i = 100;
block.f = 100.0;
strcpy(block.string,"100");
strcpy(block.end,"END");
fh = open(FILENAME, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,0666);
if(fh == -1)
{
perror(fh);
return;
}
rtn = WriteData(fh,&block,sizeof(block));
if(rtn < 0)
{
perror(FILENAME);
}
close(fh);
return 0;
}
int WriteData(int fh, void* buf, int len)
{
int written = 0; // the size of written
int val;
while(written < len)
{
val = write (fh, ((char*)buf)+written, len-written);
if(val == -1)
{
return val;
}
written += val;
}
return written;
}