Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <stdio.h>
- #define BUF_SIZE 4096
- int main() {
- DWORD bytesRead;
- char buffer[BUF_SIZE];
- // Ensure stdin is in binary mode
- _setmode(_fileno(stdin), _O_BINARY);
- HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
- while (ReadFile(hStdin, buffer, BUF_SIZE, &bytesRead, NULL) && bytesRead > 0) {
- // Process buffer[0..bytesRead-1]
- }
- return 0;
- }
- #include <unistd.h>
- #define BUF_SIZE 4096
- int main() {
- char buffer[BUF_SIZE];
- ssize_t bytesRead;
- while ((bytesRead = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0) {
- // Process buffer[0..bytesRead-1]
- }
- return 0;
- }
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #ifdef _WIN32
- #include <io.h> // _setmode(), _fileno()
- #include <fcntl.h> // _O_BINARY
- #include <windows.h> // for GetLastError()
- #else
- #include <unistd.h> // write(), STDOUT_FILENO, usleep()
- #include <errno.h> // errno
- #endif
- // write_all: repeatedly write() or fwrite() until all bytes are out
- static int write_all(const uint8_t *buf, size_t total) {
- size_t written = 0;
- while (written < total) {
- #ifdef _WIN32
- int n = _write(_fileno(stdout),
- buf + written,
- (unsigned int)(total - written));
- if (n < 0) {
- fprintf(stderr,
- "write error: code %ld\n",
- GetLastError());
- return -1;
- }
- #else
- ssize_t n = write(STDOUT_FILENO,
- buf + written,
- total - written);
- if (n < 0) {
- if (errno == EINTR) continue; // retry on signal
- perror("write");
- return -1;
- }
- #endif
- written += (size_t)n;
- }
- return 0;
- }
- int main(void) {
- // Example: allocate a 100 MiB buffer and fill it with a pattern
- size_t bufsize = 100 * 1024 * 1024;
- uint8_t *buffer = malloc(bufsize);
- if (!buffer) {
- perror("malloc");
- return EXIT_FAILURE;
- }
- for (size_t i = 0; i < bufsize; i++)
- buffer[i] = (uint8_t)(i & 0xFF);
- #ifdef _WIN32
- // Switch stdout to binary mode on Windows
- if (_setmode(_fileno(stdout), _O_BINARY) == -1) {
- fprintf(stderr, "failed to set stdout to binary mode\n");
- free(buffer);
- return EXIT_FAILURE;
- }
- #endif
- if (write_all(buffer, bufsize) != 0) {
- free(buffer);
- return EXIT_FAILURE;
- }
- // Optionally flush to ensure all data is handed off
- fflush(stdout);
- free(buffer);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment