在Linux中,使用IO标准库进行读写操作。
使用到的函数有:fopen()、fwrite()、fseek()、fread()、fclose()
代码示例:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>FILE *f = NULL;
int ret;
char buf[128] = {0};int main(void)
{f = fopen("./test.txt","r+");if (NULL == f){perror("fopen error");return 1;}ret = fwrite("hello world",1,11,f);if ( ret < 11){perror("fwrite error");fclose(f);return 1;}ret == fseek(f,0,SEEK_SET);if (-1 == ret){perror(" fseek error");fclose(f);return 1;}ret == fread(buf,1,11,f);if (11 > ret){printf("fread error or end-of-the file");fclose(f);return 1;}printf("fread %s\n",buf);fclose(f);return 0;
}
运行结果: