1.向文件中写入结构体
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
int a;
char c;
};
int main()
{
int fd;
struct Test data[2] = {{100,'a'},{101,'b'}};
struct Test data2[2];
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data,sizeof(struct Test)*2);
lseek(fd,0,SEEK_SET);
int n_read = read(fd, &data2, sizeof(struct Test)*2);
printf("read %d,%c \n",data2[0].a,data2[0].c);
printf("read %d,%c \n",data2[1].a,data2[1].c);
close(fd);
return 0;
}
2.通过C库使用fopen fread fwrite fseek fclose
//FILE *fopen(const char *path, const char *mode);
FILE *fp;
char *str = "chenlichen hen shuai";
char readBuf[128] = {0};
fp = fopen("./chen.txt","w+");
//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
//ptr buf
//size sizeof char
// geshu
// which file
fwrite(str,sizeof(char)*strlen(str),1,fp);
// fwrite(str,sizeof(char)*strlen(str),1,fp);
fseek(fp,0,SEEK_SET);
// size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
// size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
fread(readBuf,sizeof(char)*strlen(str),1,fp);
printf("read data: %s\n",readBuf);
3.用fopen fread fwrite fseek fclose向文件中写一个结构体数组
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
int a;
char c;
}
int main()
{
FILE *fp;
struct Test data = {100,'a'};
struct Test data2;
fp = fopen("./file1","w+");
int n_write = fwrite(&data,sizeof(struct Test),1,fp);
fseek(fp,0,SEEK_SET);
int n_read = fread(&data2, sizeof(struct Test), 1,fp);
printf("read %d,%c \n",data2.a,data2.c);
fclose(fp);
return 0;
}
4.fputc的使用
FILE *fp;
int i;
char *str = "wang jia hao hen shuai o!";
int len = strlen(str);
fp = fopen("./test.txt","w+");
for(i=0;i<len;i++){
fputc(*str,fp);
str++;
}
fclose(fp);
5.fgetc的使用
FILE *fp;
int i;
char c;
fp = fopen("./test.txt","r");
while(!feof(fp)){// nonezero if reach end of file
c = fgetc(fp);
printf("%c",c);
}
fclose(fp);