我想将一些数据写入文本文件,但我总是得到“错误”,因为 bytesWritten 的值为 -1。我已经调试过 dataLength 和 dataBytes 都可以,我认为我有权在桌面上创建文件。这是什么原因造成的,我该如何解决?代码如下:
void savedata(NSData *data)
{
NSInteger dataLength;
const uint8_t * dataBytes;
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
dataLength = [data length];
dataBytes = [data bytes];
NSOutputStream *fileStream = [NSOutputStream outputStreamToFileAtPath:@"~/Desktop/12.txt" append:NO];
bytesWrittenSoFar = 0;
do {
bytesWritten = [fileStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
NSLog(@"Wrong!");
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != dataLength);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSData* data = [@"sadas" dataUsingEncoding:NSUTF8StringEncoding];
savedata(data);
return 0;
}
}