简体   繁体   中英

Read Posix System Call

I'm trying to print out the contents of a file, however the program will pause at the read() function and won't continue until I hit the enter key. Once the enter key is pressed, nothing is printed to the terminal. The rest of the program is not shown, but here is the method that is causing the issue.

{
char buff[1024];
ssize_t bytesRead = 0;
int readFile, error;
if((readFile = open(file,O_RDONLY)<0))
   {
        printf("can't open %s\n",file);
        error = errno;
        return -1;
   }
do{
        memset(buff,0,1024);
        if((bytesRead=read(readFile,buff,1024))==-1)
        {
            printf("error reading file");
            error = errno;
            printf("%d",error);
        }
        else
            printf("%s",buff);
   }while(bytesRead==1024);
   printf("\n");
   close(readFile);
   return 1;
}

Alternatively, if I change the read() function to pread(file,buff,1024,0) it throws an illegal seek 29 error.

Hitting the enter key should not effect the read call unless you are reading from stdin (standard input). In that case, the input you provided - whitespace - may be printed out in the printf("%s", buff); call. If you could include some steps on how you found out that this is the method causing the issue or how you found out that it pauses at the read line (and if you are reading from /dev/stdin ), it may be easier to help.

Consequently, the same printf call may never return, if the bytes read do not contain a null and the bytesRead count is 1024 - the string in buff would not be null terminated. You can fix this by either doing buff[1023] = '\\0'; or by setting a length limit in the printf call like printf("%.1024s", buff);

do{
        memset(buff,0,1024);
        if((bytesRead=read(readFile,buff,1024))==-1)
        {
            printf("error reading file");
            error = errno;
            printf("%d",error);
        }
        else
            printf("%s",buff);
   }while(bytesRead==1024);

Your loop isn't correct. It assumes that read() fills the buffer; it fails if the file isn't a multiple of 1024 bytes; it corrupts errno before printing it; and it does unnecessary memset() operations. Honey it's a mess. It should look like this:

while ((bytesRead=read(readFile, buff, sizeof buff)) > 0)
{
    printf("%.*s", bytesRead, buff);
}
if (bytesRead < 0)
{
    error = errno;  
    perror("error reading file");
    printf("errno=%d\n",error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM