无法使用 NSFileHandle 编辑文件的第一个字节 [英] Not able to edit first byte of file using NSFileHandle
问题描述
在我的应用程序中,我使用 NSFileHandle 来编辑一些文件,但它没有编辑.
以下是代码:带有注释和日志输出
//初始化文件管理器NSFileManager *filemgr;filemgr = [NSFileManager defaultManager];//初始化文件句柄NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];//检查文件是否可写if ([filemgr isWritableFileAtPath:filePath] == YES)NSLog(@"文件可写");别的NSLog(@"文件是只读的");//读取文件的第一个字节NSData *decryptData = [fileHandle readDataOfLength:1];//打印第一个字节 &长度NSLog(@"data1: %d %@",[decryptData length],decryptData);//数据2:1 <37>//替换第一个字节NSData *zeroData = 0;[fileHandle writeData:zeroData];//读取第一个字节进行检查解密数据 = [fileHandle readDataOfLength:1];//打印第一个字节NSLog(@"data2: %d %@",[decryptData length],decryptData);//数据2:1<00>NSURL *fileUrl=[NSURL fileURLWithPath:filePath];NSLog(@"fileUrl:%@",fileUrl);[fileHandle closeFile];
有什么建议吗?
如果你想用 NSFileHandle
写,你需要打开文件进行读写:
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
如果您不确定指定路径上的文件是否可写,您应该在打开它之前检查相应的权限,如果权限不足以满足您的需要,则向用户显示错误.>
此外,要写入数据,您需要创建一个 NSData
实例.代码行
NSData *zeroData = 0;
正在创建一个 nil
对象,而不是一个包含零字节的对象.我想你想要
int8_t 零 = 0;NSData *zeroData = [NSData dataWithBytes:&zero length:1];
In my app, I am using NSFileHandle to edit some file but it is not editing.
Below is the code: with comments & logs output
//Initialize file manager
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
//Initialize file handle
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
//Check if file is writable
if ([filemgr isWritableFileAtPath:filePath] == YES)
NSLog (@"File is writable");
else
NSLog (@"File is read only");
//Read 1st byte of file
NSData *decryptData = [fileHandle readDataOfLength:1];
//Print first byte & length
NSLog(@"data1: %d %@",[decryptData length],decryptData); //data2: 1 <37>
//Replace 1st byte
NSData *zeroData = 0;
[fileHandle writeData:zeroData];
//Read 1st byte to check
decryptData = [fileHandle readDataOfLength:1];
//Print first byte
NSLog(@"data2: %d %@",[decryptData length],decryptData); //data2: 1 <00>
NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
NSLog(@"fileUrl:%@",fileUrl);
[fileHandle closeFile];
Any Suggestions?
If you want to write using NSFileHandle
you need to open the file for writing as well as reading:
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
If you aren't sure if the file at the specified path is writable, you should check for the appropriate permissions before you open it and display an error to the user if they are insufficient for what you need to do.
Also, to write data you need to create an instance of NSData
. The line of code
NSData *zeroData = 0;
is creating a nil
object, not an object containing a zero byte. I think you want
int8_t zero = 0;
NSData *zeroData = [NSData dataWithBytes:&zero length:1];
这篇关于无法使用 NSFileHandle 编辑文件的第一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!