How to read a string in Linux by bytes?

In Linux, you can read strings byte by byte using the standard C library function fread.

Here is a sample code:

#include <stdio.h>

#define BUFFER_SIZE 256

int main() {
    FILE *file;
    char buffer[BUFFER_SIZE];
    int bytesRead;

    // 打开文件
    file = fopen("file.txt", "rb");

    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    // 读取文件内容
    bytesRead = fread(buffer, 1, BUFFER_SIZE-1, file);
    buffer[bytesRead] = '\0'; // 将字符串结尾设置为'\0'

    // 输出读取到的字符串
    printf("读取到的内容:%s\n", buffer);

    // 关闭文件
    fclose(file);

    return 0;
}

This sample code opens a file named file.txt, reads bytes from the file, up to a maximum of BUFFER_SIZE-1 bytes (the last byte is used to store the string’s end \0). The bytes read are stored in the buffer array and printed using the printf function.

Save the sample code as read_bytes.c file, then compile and run it with the following commands:

gcc -o read_bytes read_bytes.c
./read_bytes

This way, you can read the string byte by byte.

bannerAds