基本文件操作 - Create and write
- 基本文件操作函数
- open()
- read()
- write()
- close()
- Iseek()
代码块
代码块语法遵循标准markdown代码,例如:
- create and write file Test_10_2b.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 ReadData(int fh, void* buf, int len);
struct data{
int i;
float f;
char string[MAX_STRING_LENGTH+1];
char end[4];
};
int main(){
int i,j;
int fh,rtn;
struct data block;
block.i = 100;
block.f = 100.0;
strcpy(block.string,"100");
strcpy(block.end,"END");
fh = open(FILENAME,O_RDONLY | O_BINARY);
if(fh == -1)
{
perror(FILENAME);
return;
}
rtn = ReadData(fh, &block, sizeof(block));
if(rtn == -1)
{
perror(FILENAME);
}
printf("The int is %d.\n",block.i);
printf("The float is %f.\n",block.f);
printf("The string is %s.\n",block.string);
printf("The end is %s.\n",block.end);
close(fh);
return 0;
}
int ReadData(int fh, void* buf, int len)
{
int readBytes = 0;
int val;
while(readBytes < len)
{
val = read(fh,((char*)buf)+readBytes,len-readBytes);
if(val == -1)
{
return val;
}
readBytes += val;
}
return readBytes;
}