#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sysexits.h>
#define die(E,...) ({ \
fprintf(stderr,__VA_ARGS__); \
exit(E); })
void reverse(char* a,size_t z) {
for(; z>=2 ;a++,z-=2) {
char t=*a; *a=a[z-1]; a[z-1]=t; } }
int main(void) {
size_t z=16,i=0;
char *a=malloc(z), *p=0;
for(;;) {
for(;;) {
ssize_t n = read(0,a+i,z-i);
if(n<0) die(EX_IOERR,"input error: %m");
if(n+i==0) exit(0);
if(n==0) die(EX_DATAERR,"error: %zu bytes of garbage at end of file",i);
p = memchr(a,'\n', (i += n) );
if(p) break;
if(i > z/2) {
a = realloc(a, (z = z+z/2) );
if(!a) die(EX_OSERR,"realloc(%zu bytes): %m",z); } }
while(p) {
reverse(a,p-a);
fwrite(a,p-a+1,1,stdout);
memmove(a,p+1, (i -= p-a+1) );
p = memchr(a,'\n',i); } } }
This produces: $ ./a.out
cat
tac
warning: incompatible implicit declaration of built-in function
noitcnuf ni-tliub fo noitaralced ticilpmi elbitapmocni :gninraw
naïve resumé
�muser ev�an
> i guarantee the c++ code will be easier to write and understand than any c code.Put up or shut up, as the saying goes. At the very least it ought to be easy to abstract out some of the memory allocation and file handling to use C++ builtins, and I'd be interested to see what other improvements you can manage.
Edit: 0: Exercise for the reader: consider the input "abXc", where 'X' is some as-yet-undefined codepoint that will, at some point in the future, be defined as either a combining diacritic, or a standalone character. If 'X' is a character, the output should be "cXba", but if it's a diacritic, the output should be "cbXa". The information about which (mutually-exclusive) output is correct does not exist yet.
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t len = 0, cap = 0;
char *buffer = NULL;
int c;
while ((c = getchar()) != EOF) {
if (len >= cap) {
cap = (cap << 1) + 1;
{
char *newbuf = realloc(buffer, cap);
if (!newbuf) {
fprintf(stderr, "Could not reallocate to %zu. Printing what I've got.", cap);
break;
}
buffer = newbuf;
}
}
buffer[len++] = (char)c;
}
while (len --> 0) {
if (putchar(buffer[len]) == EOF) {
fprintf(stderr, "Output failure.");
return 1;
}
}
free(buffer);
return 0;
}
Most of the verbosity here is in correctly handling errors, something that isn't much easier to do in C++. (Be warned: I haven't tested this code.)compare with using std::string and std::getline - easy to use and battle-hardened.
What would the equivalent code look like in C++, handling EOF and OOM conditions appropriately?
string input;
try {
if ( cin.getline ( input ) ) {
// ok read input, do something with it
}
else {
// some sort of predictable error - look at state of cin to diagnose EOF
}
}
catch (...) { /// something terrible happened - as hard to recover as it would be in c
}I also looked up whether the cast from int to char is safe. Seems that it is not, but probably fine in practice https://stackoverflow.com/questions/19250521/best-way-to-por...
Of course all bets are off when someone tries to reverse emoji soup with this, but I am not knowledgeable enough about this topic to claim whether a general solution is even possible.
The correct way to reverse a Unicode string is to blit it back to front.
Addendum: a real C programmer helped me write (i.e., wrote most of) the following program:
#include <skalibs/skalibs.h>
int main() {
stralloc sa = STRALLOC_ZERO;
slurp(&sa, 0);
stralloc_reverse(&sa);
if (allwrite(1, sa.s, sa.len) < sa.len) {
strerror_diefusys(1, "output everything");
}
}
In the event of an allocation failure, this program will output nothing; other than that, it's the same as my C program above. Perhaps the problem isn't C, but its standard library?That's certainly at least a factor. In Rust, the "reverse a string byte by byte" bit could look like:
let reversed_string = String::from_utf8(some_string.bytes().rev().collect::<Vec<u8>>())?;
This is just what I thought of first. Peeking at the standard library examples, this one is fun: unsafe {
let vec = some_string.as_mut_vec();
vec.reverse();
}
This is unsafe because you may create invalid utf8, but we've already established that's not something we care about, so...But yeah stuff like this isn't impossible in C, though you'd not have method call syntax, of course. Rust's libraries are just richer here.
perhaps i will start it up again, now it is just me, and not exactly happy, but not depressed.
That will depend on how you define "understand". For a superficial level of understanding, you might be right. But the C++ code will make use of many concepts that would take a while to explain, for example references, classes, inheritance, templates, operator overloading, STL, and probably a bunch of other things I forgot.