Skip to content

Instantly share code, notes, and snippets.

@MiniAppleTheApple
Last active December 2, 2022 01:24
Show Gist options
  • Select an option

  • Save MiniAppleTheApple/c16d842213e8b9861395798287a853ca to your computer and use it in GitHub Desktop.

Select an option

Save MiniAppleTheApple/c16d842213e8b9861395798287a853ca to your computer and use it in GitHub Desktop.
Cat clone
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define BUFFER_CAPACITY 10
#define DEFAULT_BUFFER { \
calloc(BUFFER_CAPACITY, sizeof(char)), \
BUFFER_CAPACITY, \
} \
typedef struct {
char* data;
size_t capacity;
size_t length;
} buffer_t;
void append(buffer_t* buffer, char elem) {
if (buffer->capacity < buffer->length + 1) {
buffer->capacity *= 2;
buffer->data = realloc(buffer->data, sizeof(char) * buffer->capacity + 1);
}
buffer->data[buffer->length] = elem;
buffer->length += 1;
}
void concat(buffer_t* buffer, char* str, size_t size) {
for (int j = 0;j < size;j++) {
append(buffer, str[j]);
}
}
int main(int argc, char** argv) {
if (argc < 2) {
while (true) {
char ch = getc(stdin);
putc(ch, stdout);
}
}
const char* file_not_found = "cat clone: %s: No such file or directory\n";
buffer_t buffer = DEFAULT_BUFFER;
for (int i = 1;i < argc;i++) {
FILE* file = fopen(argv[i], "r");
if (file == NULL) {
size_t size = strlen(file_not_found) - 1 + strlen(argv[i]);
char* str = calloc(size, sizeof(char));
snprintf(str, size, file_not_found, argv[i]);
concat(&buffer, str, size);
continue;
}
char ch = fgetc(file);
while(ch != EOF) {
append(&buffer, ch);
ch = fgetc(file);
}
fclose(file);
}
printf("%s", buffer.data);
}
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
int main(int argc, char** argv) {
if (argc < 2) {
std::string str;
while (true) {
std::cin >> str;
std::cout << str << "\n";
}
}
std::ostringstream buffer;
for (int i = 1;i < argc;i++) {
std::ifstream file(argv[i]);
if (file.is_open()) {
std::string temp;
file >> temp;
buffer << temp << "\n";
} else {
buffer << "cat clone: " << argv[i] << ": No such file or directory\n";
}
}
std::cout << buffer.str();
}
use std::fs;
use std::env;
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line
}
fn main() {
let mut buffer: Vec<String> = vec![];
let args = env::args()
.skip(1);
while args.len() < 1 {
print!("{}", read_line());
}
args.for_each(|file_name| {
let file_contents = fs::read_to_string(&file_name);
match file_contents {
Ok(x) => buffer.push(x),
Err(_) => buffer.push(format!("cat clone: {}: No such file or directory\n", &file_name).to_string()),
}
});
print!("{}", buffer.join(""));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment