簡體   English   中英

使用C中的read(2)函數從緩沖區打印

[英]Printing from a buffer using the read(2) function in C

我正在嘗試使用讀取功能讀取位,但不確定如何使用緩沖區將結果打印出來。

目前的代碼片段如下

 char *infile = argv[1];
 char *ptr = buff;
 int fd = open(infile, O_RDONLY); /* read only */
 assert(fd > -1);
 char n;
 while((n = read(fd, ptr, SIZE)) > 0){ /*loops that reads the file                                until it returns empty */
   printf(ptr);
 }

讀入ptr的數據可能包含\\0字節,格式說明符,並且不一定\\0終止。 所有不使用printf(ptr)充分理由。 代替:

// char n;
ssize_t n;
while((n = read(fd, ptr, SIZE)) > 0) { 
  ssize_t i;
  for (i = 0; i < n; i++) {
    printf(" %02hhX", ptr[i]);
    // On older compilers use --> printf(" %02X", (unsigned) ptr[i]);
  }
}

這是為您完成工作的代碼:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>

#define SIZE        1024

int main(int argc, char* argv[])
{
    char *infile = "Text.txt";
    char ptrBuffer[SIZE];
    int fd = open(infile, O_RDONLY); /* read only */
    assert(fd > -1);
    int n;
    while((n = read(fd, ptrBuffer, SIZE)) > 0){ /*loops that reads the file                                until it returns empty */
        printf("%s", ptrBuffer);
        memset(ptrBuffer, 0, SIZE);
    }

    return 0;
}

您可以讀取文件名作為參數。

即使ptr是字符串,也需要使用printf("%s", ptr); ,而不是printf(ptr);

但是,致電后

read(fd, ptr, SIZE)

ptr很少是字符串(字符串需要以空值結尾)。 您需要使用循環並選擇所需的格式。 例如:

for (int i = 0; i < n; i++)
    printf("%02X ", *ptr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM