0

I am having a strange problem trying to read and write 9k bytes with open(), read() and write(). When I attempt to write 9k to a file and read it back, the data only goes up to 2250 bytes. After that everything is zeros.

Here is my code (except for the filename which isn't relevant, I'm just putting it to 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);

And here is the strange output:

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

As you can see on the last line, the data suddenly goes to zero.

Any ideas what I might be doing wrong? The thing that really gets me is that both the read() and write() return 9000.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Locksleyu
  • 5,192
  • 8
  • 52
  • 77

1 Answers1

0

As mentioned by ughoavgfhw (Thanks!) the problem was I was mixing up bytes and ints. 9000 bytes is the same thing as 2250 ints, since each int is 4 bytes.

Locksleyu
  • 5,192
  • 8
  • 52
  • 77