免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1231 | 回复: 2
打印 上一主题 下一主题

[学习分享] linux程序设计 第4版上的例题. [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-09-03 16:12 |只看该作者 |倒序浏览
刚刚看这本书 ,看到一个例题是"文件复制程序"
如下:
#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

求指点

论坛徽章:
0
2 [报告]
发表于 2013-09-04 13:24 |只看该作者
居然没有人回答我 ,其实是因为while循环语句最后多了一个分号

论坛徽章:
0
3 [报告]
发表于 2013-09-05 12:44 |只看该作者
哈哈,楼主不够细心
而且程序不规范
1:open系统调用是有可能打不开的,打不开怎么办?
2:建议while后面空一空格,while的花括号去掉
3:建议main函数写成int main(int argc, char **argv),即使用不到命令行
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP