Types of Files
- Regular File
下面的示例程序中用到了大多数上面讲到的系统调用
***************************************************************
/*filedes_io.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
char sample1[] = "This is sample data 1/n";
char sample2[] = "This is sample data 2/n";
char data[16];
main()
{
int fd;
int rc;
struct stat statbuf;
/*Create the file*/
printf("Creating file/n");
fd = open("junk.out", O_WRONLY|O_CREAT|O_TRUNC, 0666);
assert(fd>=0);
rc = write(fd, sample1, strlen(sample1));
assert(rc == strlen(sample1));
close(fd);
/*Append to the file*/
printf("Appending to file/n");
fd = open("junk.out", O_WRONLY|O_APPEND);
assert(fd>=0);
printf("locking file/n");
rc = flock(fd, LOCK_EX);
assert(rc == 0);
/*sleep so you can try running two copies at one time*/
printf("sleeping for 10 senconds/n");
sleep(10);
printf("writting data/n");
rc = write(fd, sample2, strlen(sample2));
assert(rc == strlen(sample2));
printf(unlocking file/n);
rc = flock(fd, LOCK_UN);
assert(rc == 0);
close(fd);
/*Read the file*/
printf("Reading file/n");
fd = open("junk.out", O_RDONLY);
assert(fd>=0);
while(1){
rc = read(fd, data, sizeof(data));
if(rc>0){
data[rc] = 0; /*terminate string*/
printf("Data read (rc=%d):<%s>/n", rc, data);
}else if(rc == 0){
printf("End of file read/n");
break;
}else{
perror("read error");
break;
}
}
close(fd);
/*Fiddle with inode*/
printf("Fiddling with inode/n");
fd = open("junk.out", O_RDONLY);
assert(fd>=0);
printf("changing file mode");
rc = fchmod(fd, 0600);
assert(rc == 0);
if(getuid() == 0){
printf("changing file owner/n");
/*If we are root, change file to owner nobody,*/
/*group nobody(assuming nobody == 99)*/
rc = fchmod(fd, 99, 99);
assert(rc == 0);
}else{
printf("not changing file owner/n");
}
fstat(fd, &statbuf);
printf("file mode = %o (octal)/n", statbuf.st_mode);
printf("Owner uid = %d/n", statbuf.st_uid);
printf("Owner gid = %d/n", statbuf.st_gid);
close(fd);
}
- Tape I/O
- Serial port I/O
- Printer Port
- Sound Card