t;stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char const *argv[]) {
if ( argc != 2 ) {
printf("usage:%s %s\n", argv[0], "filename");
return -1;
}
int fd = -1;
fd = open( argv[1], O_RDWR );
if( -1 == fd ) {
printf("文件打开失败,错误号:%d\n", errno );
perror( "open" );
return -1;
}else {
printf("文件打开成功\n");
}
//把指针移动到文件末尾,就是文件的大小
int count = lseek( fd, 0, SEEK_END );
printf("文件大小为%d\n", count);
close( fd );
return 0;
}
------------------------------------------分割线------------------------------------------
一、同一个进程,多次打开同一个文件,然后读出内容的结果是: 分别读【我们使用open两次打开同一个文件时,fd1和fd2所对应的文件指针是不同的2个独立的指针】
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char const *argv[]) {
int fd1 = -1;
int fd2 = -1;
char buf1[20] = {0};
char buf2[20] = {0};
int count1 = 0;
int count2 = 0;
fd1 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd1=%d\n", fd1);
}
count1 = read( fd1, buf1, 5 );
if ( -1 == count1 ) {
printf( "文件读取失败\n" );
perror( "read" );
}else {
printf( "文件读取成功,读取的内容是%s\n", buf1 );
}
fd2 = open( "ghostwu.txt", O_RDWR );
if ( -1 == fd1 ) {
printf("文件打开失败\n");
perror( "open" );
return -1;
}else {
printf("文件打开成功,fd2=%d\n", fd1);
}
count2 = read( fd2, buf2, 10 );
if ( -1 == count2 ) {
printf( "文件读取失败\n" );
perror( "read" );
}else {
printf( "文件读取成功,读取的内容是%s\n", buf2 );
}
close( fd1 );
close( fd2 );
return 0;
}
二、同一个进程,多次打开同一个文件,然后写入内容的结果是: 分别写,当使用O_APPEND,就是接着写
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int fd1 = -1;
int fd2 = -1;
char buf1[] = "ghost";
char buf2[] = "wu";
int count1 = 0;
int count2 = 0;
fd1 = open( "ghostwu.txt", O_RDWR );
if (