2015-05-18 39 views
-2

我试图教自己(痛苦)如何在目标c中执行文件I/O。以下代码旨在让用户从stdin输入文件名,然后使用该名称创建NSFileManager。如果我将文件名作为NSString进行硬编码(在注释代码@“barney.txt”中显示),代码将起作用。但是,如果我使用与stdin相同的文件名,则不会出现任何情况。该程序将NSLog输出名称该文件。但是,在文件管理器没有骰子来自标准输入输出文件NSFileManager的文件名objective-c

的。我需要帮助。

谢谢, 马克·阿林

enter code here 

#import <Foundation/Foundation.h> 


int main (int argc, char ** argv) 
{ 
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

//NSString * fName = @"barney.txt"; 
NSFileManager * fm; 
//NSDictionary *attr; 

NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput]; 
NSLog(@"Created file handle..."); 
NSLog(@"Enter File Name"); 
NSData *inputData = [input availableData]; 
NSLog(@"Created NSData object"); 
NSString *fName = [[NSString alloc] initWithData:inputData    encoding:NSUTF8StringEncoding]; 
NSLog(@"Created NSString object"); 
NSLog(@"You entered %@ as the name\n", fName); 
fm = [[NSFileManager alloc] init ]; //defaultManager 

if (fm == nil) 
{ 
NSLog(@"Failed to create file manager object\n"); 

      } 
if ([fm fileExistsAtPath:fName] == YES){ 
NSLog(@"File Exists!"); 
NSLog(@"%p", fm); 
} else 
    { 
NSLog(@"File Appears not to exist"); 

} 
[fm release]; 
[pool drain]; 
return 0; 
} 
+0

实际问题是什么?你看到了哪些日志? – rmaddy

+0

顺便说一句 - 如果你正在玩命令行级代码并处理'stdin',为什么你使用iOS,而不是在Mac上作为OS X应用程序来执行此操作? – rmaddy

+0

实际的问题是程序打印“文件似乎不存在”。 –

回答

0

使用标准输入加上一个“\ n”在字符串的结尾。这会混淆搜索。如果删除换行符,代码将按预期运行。

相关问题