0

我在尝试使用 open()、read() 和 write() 读写 9k 字节时遇到了一个奇怪的问题。当我尝试将 9k 写入文件并将其读回时,数据最多只能达到 2250 字节。在那之后一切都归零。

这是我的代码(除了不相关的文件名,我只是把它放到 NSDocumentDirectory 中):

int fp = open([appFile cStringUsingEncoding:NSASCIIStringEncoding], O_RDWR | O_CREAT, 0644);

[_detailViewController log:@"first open() returns %i (err: %i)", fp, errno];

 int data2[10000];
 int data3[10000];

 for (int i=0;i<10000;i++) data2[i] = 1;

 [_detailViewController log:@"resetting seek to 0"];

 int seekPos = lseek(fp, 0, SEEK_SET);

 result = write(fp, data2, 9000);

 [_detailViewController log:@"wrote 9k, result is %i", result];

 [_detailViewController log:@"resetting seek to 0"];

 seekPos = lseek(fp, 0, SEEK_SET);

 result = read(fp, data3, 9000);

 [_detailViewController log:@"read 9k, result is %i", result];

 [_detailViewController log:@"values of data2[2248-2252] = 0x%x 0x%x 0x%x 0x%x 0x%x", data2[2248], data2[2249], data2[2250], data2[2251], data2[2252]];

 [_detailViewController log:@"values of data3[2248-2252] = 0x%x 0x%x 0x%x 0x%x 0x%x", data3[2248], data3[2249], data3[2250], data3[2251], data3[2252]];

 close(fp);

这是奇怪的输出:

2013-02-13 14:08:38.290 FileTester[2800:907] first open() returns 6 (err: 3)
2013-02-13 14:08:38.295 FileTester[2800:907] resetting seek to 0    
2013-02-13 14:08:38.301 FileTester[2800:907] wrote 9k, result is 9000
2013-02-13 14:08:38.306 FileTester[2800:907] resetting seek to 0
2013-02-13 14:08:38.311 FileTester[2800:907] read 9k, result is 9000
2013-02-13 14:08:38.319 FileTester[2800:907] values of data2[2248-2252] = 0x1 0x1 0x1 0x1 0x1
2013-02-13 14:08:38.327 FileTester[2800:907] values of data3[2248-2252] = 0x1 0x1 0x0 0x0 0x0

正如您在最后一行看到的,数据突然变为零。

有什么想法我可能做错了吗?真正让我感动的是 read() 和 write() 都返回 9000。

4

1 回答 1

0

正如 ughoavgfhw (谢谢!)所提到的,问题是我混淆了字节和整数。9000 字节与 2250 个整数是一样的,因为每个整数是 4 个字节。

于 2013-02-15T18:19:18.873 回答