Friday, December 12, 2008

read and lseek problem in win32

when i try to convert code from unix to win32, i encounter problem on read and lseek

below code show the problem

#include "stdio.h"
#include "io.h"
#include "fcntl.h"
#include "stdlib.h"

int open_lseek_test(char* file)
{
int fd;
int len;
int rc;
char *mem;
char data[1000];
fd = open(file, O_RDONLY);
//check total byte
len = lseek(fd, 0, SEEK_END);
mem = (char*)malloc(len+1);
rc = lseek(fd, 0, SEEK_SET);
rc = read(fd, mem, len);
printf("lseek END = %d read len = %d\n",len,rc);
free(mem);
if(rc != len)
{
return -1;
}
else
{
return 0;
}
}

int main()
{
char* filename = "abc.txt";
FILE* fh = fopen(filename,"w");
fprintf(fh,"testing1");
fprintf(fh,"testing2");
fclose(fh);

if(open_lseek_test(filename)==0)
{
printf("1 - success\n");
}
else
{
printf("1 - open and lseek not match\n");
}

fh = fopen(filename,"w");
fprintf(fh,"testing1\n");
fprintf(fh,"testing2\n");
fclose(fh);

if(open_lseek_test(filename)==0)
{
printf("2 - success\n");
}
else
{
printf("2 - open and lseek not match\n");
}
return 0;
}
Result show:
lseek END = 16 read len = 16
1 - success
lseek END = 20 read len = 18
2 - open and lseek not match

Reason:
if using fprintf or notepad to insert a new row to text file, by default, "\r\n" will be insert to text file.
lseek function would count the "\r" character, but read function would ignore "\r"