背景:
最近遇到個問題,在獲取航拍實時數(shù)據(jù)做圖像處理的時候,有時候處理結(jié)果不正確(圖像中有目標物,沒有識別出來)。就需要在畫面上添加一個按鈕,點擊來保存當時的畫面到沙盒中。
但是,寫入的數(shù)據(jù),需要放到Matlab下生成圖片。所以,使用OC自帶的writeToFile不方便實用。(將Array writeToFile 到 txt后,里面的格式是XML。。。)
1、首先獲取當前時間,用作文件名來區(qū)分保存的文件。
```
NSString*timeStr = [NSStringstringWithFormat:@"%@",[NSDatedate]];
```
2、獲取文件路徑
```
// 獲取沙盒documents路徑
NSMutableString *documentsPath = [NSMutableString stringWithString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
// 拼接成對應(yīng)的文件路徑名
[documentsPath appendFormat:@"/rData_%@.txt",timeStr];
```
3、NSString轉(zhuǎn)成C的指針string
const char *filePath = [documentsPath UTF8String];
4、打開文件(若不存在則創(chuàng)建文件)
//? ? ? ? "w" 寫入方式打開,將文件指針指向文件頭并將文件大小截為零。如果文件不存在則嘗試創(chuàng)建之。
//? ? ? ? "w+" 讀寫方式打開,將文件指針指向文件頭并將文件大小截為零。如果文件不存在則嘗試創(chuàng)建之。
//? ? ? ? "a" 寫入方式打開,將文件指針指向文件末尾。如果文件不存在則嘗試創(chuàng)建之。
//? ? ? ? "a+" 讀寫方式打開,將文件指針指向文件末尾。如果文件不存在則嘗試創(chuàng)建之。
FILE *fp = fopen(filePath, "w+");
5、寫入
// _RArray數(shù)據(jù)是 NSNumber numberWithInt: 寫入,對應(yīng)用intValue取出來
int a =[_RArray[j][k] intValue];
fprintf(fp, "%d\t", a);
6、關(guān)閉文件
fclose(fp);
由于有RGB三個通道,循環(huán)三次依次寫入三個文件。完整代碼如下
NSString *timeStr = [NSString stringWithFormat:@"%@",[NSDate date]];
for (NSInteger i = 1; i <= 3; i++)
{
// 獲取路徑
NSMutableString *documentsPath = [NSMutableString stringWithString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
switch (i) {
case 1:
[documentsPath appendFormat:@"/rData_%@.txt",timeStr];
break;
case 2:
[documentsPath appendFormat:@"/gData_%@.txt",timeStr];
break;
case 3:
[documentsPath appendFormat:@"/bData_%@.txt",timeStr];
break;
default:
break;
}
const char *filePath = [documentsPath UTF8String];
NSLog(@"documentsPath : %@",documentsPath);
FILE *fp = fopen(filePath, "w+");
switch (i)
{
case 1:
for (NSInteger j = 0; j < _RArray.count; j++) {
for (NSInteger k = 0; k < [_RArray[0] count]; k++) {
int a =[_RArray[j][k] intValue];
//? ? ? ? ? ? ? ? ? ? ? ? ? ? printf("%d\t",a);
fprintf(fp, "%d\t", a);
}
fprintf(fp, "\n");
}
break;
case 2:
for (NSInteger j = 0; j < _GArray.count; j++) {
for (NSInteger k = 0; k < [_GArray[0] count]; k++) {
int a =[_GArray[j][k] intValue];
fprintf(fp, "%d\t", a);}
fprintf(fp, "\n");
}
break;
case 3:
for (NSInteger j = 0; j < _BArray.count; j++) {
for (NSInteger k = 0; k < [_BArray[0] count]; k++) {
int a =[_BArray[j][k] intValue];
fprintf(fp, "%d\t", a);}
fprintf(fp, "\n");
}
break;
default:
break;
}
fclose(fp);
查看寫入到沙盒的文件







