Objective-C:用命令行参数的格式对文件进行IO操作

 1 //  main.m
 2 
 3 //  03-copyFile
 4 
 5 //  Created by ma c on 15/8/24.
 6 
 7 //  Copyright (c) 2015年. All rights reserved.
 8 
 9 #import <Foundation/Foundation.h>
10 
11  int main(int argc, const char * argv[])
12 
13 {
14     @autoreleasepool
15     {
16         //1、检查参数
17         if(argc < 3)
18         {
19             NSLog(@"用法:命令行 源文件 目标文件");
20             return -1;
21         }
22 
23 
24         //2.检查源文件是否存在
25 
26         NSString *file1 = [NSString stringWithUTF8String:argv[1]];
27 
28         NSString *file2 = [NSString stringWithUTF8String:argv[2]];
29 
30         
31 
32         NSFileManager *fm = [NSFileManager defaultManager];
33 
34         BOOL isDirectory = YES;
35        
36 
37         if(![fm fileExistsAtPath:file1 isDirectory:&isDirectory])
38         {
39             NSLog(@"源文件不存在");
40             return -1;
41         }
42         else
43         {
44             if(isDirectory)
45             {
46                 NSLog(@"不能拷贝目录");
47                 return -1;
48             }
49 
50 
51             //3.判断目标文件是否存在
52             if(![fm fileExistsAtPath:file2 isDirectory:NULL])
53             {
54                 [fm createFileAtPath:file2 contents:nil attributes:nil];
55             }
56             else
57             {
58                 NSLog(@"是否要覆盖文件? 'y' or 'n'");
59                 char answer = getchar();
60                 if(answer != 'y')
61                 {
62                     return -1;
63                 }
64             }
65 
66      
67 
68             //4.文件拷贝
69             NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:file1];
70 
71             NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:file2];
72             if(in && out)
73             {
74                 while(YES)
75                 {
76                     NSData *data = [in readDataOfLength:100];
77                     if(!data || [data length]<=0)
78                     {
79                         break;
80                     }
81                     [out writeData:data];
82                 }
83             }
84             else
85             {
86                 NSLog(@"文件打开失败");
87             }
88 
89             
90 
91             //5.关闭文件
92             [in closeFile];
93             [out closeFile];
94         }
95     }
96     return 0;
97 }
98 
99  

 

posted @ 2015-08-24 21:00  XYQ全哥  阅读(457)  评论(0编辑  收藏  举报