2023年12月18日发(作者:)

实验三 缓冲IO和特殊文件

实验目的

1.了解和掌握基于流的文件I/O程序设计

2.掌握特殊文件的程序设计方法

实验内容

1. 设计一程序,要求用带缓存的流文件I/O操作,在“./tmp”目录下,打开名称为“tmpfile”的文件。如果该文件不存在,则创建此文件;如果存在,将文件清空后关闭。

#include

#include

int main()

{

FILE * fp;

if((fp=fopen("./tmp/tmpfile","w+"))==NULL)

perror("open file failed");

else

{

printf("file openedn");

fclose(fp);

}

}

2.设计一程序,要求用带缓存的流文件I/O操作,利用fputc函数把键盘上输入的字符串写入文件“./tmp/2-2tmp”,如果该文件不存在,则创建此文件;多次运行程序,多次输入字符串后,文件“/tmp/2-2tmp”中只保存最后一次输入的字符串(若要保存全部输入的字符串,如何改写程序?)。

#include

main()

{

FILE *fp;

char ch;

if((fp=fopen("./tmp/2-2tmp","w+"))==NULL)

perror("file open error");

else

{

printf("input the string:n");

while(ch!='n')

fputc((ch=fgetc(stdin)),fp);

fclose(fp);

}

}

若要保存全部输入的字符串,将if((fp=fopen("./tmp/2-2tmp","w+"))==NULL)中"w+"改为"a+"。

3.设计一程序,要求新建一个目录newdir和它的子目录childdir,预设权限为rwx—x—x,打开newdir目录并输出该目录下的目录名和inode,关闭该目录文件。

#include

#include

#include

#include

main()

{

DIR *dir;int d;

struct dirent *ptr;

if((d=mkdir("./newdir",0711))==-1)

perror("directory created failed!");

if((d=mkdir("./newdir/childdir",0711))==-1)

perror("directory created failed!");

else

{

dir=opendir("./newdir");

while ((ptr=readdir(dir))!=NULL)

printf("new dir is:%sinode :%dn",ptr->d_name,ptr->d_ino);

closedir(dir);

}

}

4.设计一程序,要求为“/bin/ls”文件建立一个软链接“ls1”和一个硬链接“ls2”,并查看两个链接文件和“/bin/ls”文件,并运行./ls1和./ls2,查看结果。

#include

#include

main()

{

symlink("/bin/ls","./ls1");

link("/bin/ls","ls2");

system("ls ./ls1 -l");

system("ls ./ls2 -l");

system("ls /bin/ls");

}