- 论坛徽章:
- 0
|
刚刚看这本书 ,看到一个例题是"文件复制程序"
如下:
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
int main(void)
{
char c;
int in,out;
in = open("file_in", O_RDONLY);
out = open("file_out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while(read(in, &c, 1) == 1);
{
write(out, &c, 1);
}
exit(0);
}
其中file_in是我事先建立好的一个文本文件.内容是我随便打的一些字符.
问题是,我按照书上写的程序竟然不能复制这个文件.奇怪啊.
程序执行结果是这样的:
-rw-r--r-- 1 root root 53 2013-09-03 15:51 file_in
-rw------- 1 root root 1 2013-09-03 15:53 file_out
另一个优化的例子:
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
int main(void)
{
char block[1024];
int in,out;
int nread;
in = open("file_in", O_RDONLY);
out = open("file_out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while((nread = read(in, block, sizeof(block))) > 0);
{
write(out, block, nread);
}
exit(0);
}
执行后的结果是这样:
-rw-r--r-- 1 root root 53 2013-09-03 15:51 file_in
-rw------- 1 root root 0 2013-09-03 15:53 file_out
程序跟书上的一样.我的linux环境是:
[ root:~ ]# uname -a
Linux ubuntu 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux
另一个环境是:
[root@Linux237 ~]# uname -a
Linux Linux237 2.6.23.1-42.fc8 #1 SMP Tue Oct 30 13:55:12 EDT 2007 i686 i686 i386 GNU/Linux
求指点 |
|