Link Search Menu Expand Document

write.c

Below is our example code of using write.

#include <unistd.h>
#include <stdio.h>

int main() {
    char buffer[100];
    ssize_t count = write(1, buffer, 100);
    printf("\nWrote %ld bytes!\n", count);
}

pig.c

Here is the completed English to Pig Latin converter. Once compiled and run, it converts what is read on standard input and prints it to standard output.

#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>

// Returns a pointer to the first occurrence of a vowel in the word
const char *findVowel(const char *word) {
    const char *ans = strpbrk(word, "aeiouAEIOU");
    if (ans != NULL) return ans;
    return word;
}

// Prints the conversion of a word in Pig Latin
void showPig(const char *word) {
    const char *vowel = findVowel(word);
    printf("%s", vowel); // ig
    fwrite(word, sizeof(char), vowel - word, stdout);// p
    printf("%s", "ay"); // ay
}

int main(int argc, const char *argv[]) {
    char buffer[1500]; // watch buffer overflow attack!
    int index = 0;

    // Read until there is nothing left (EOF)
    while (read(0, buffer+index, 1) == 1) {
  
        if(isalpha(buffer[index])) {
            // If it is a letter, then build the buffer with the word
            index += 1;
        } else {
            // If it is not a letter, print the buffer in Pig Latin
            // form, then write this character to the output after the
            // word we read in.  Reset our position in the buffer to 0.
            char keepme = buffer[index];
            if (index > 0) {
                buffer[index] = '\0';
                showPig(buffer);
            }
            fwrite(&keepme, sizeof(char), 1, stdout);
            index = 0;
        }
    }
}

Copyright © 2022 John Hott, portions Luther Tychonievich.
Released under the CC-BY-NC-SA 4.0 license.
Creative Commons License