Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Created August 29, 2020 10:20
Show Gist options
  • Save cs-fedy/f9e495f1f714a00e62a07713285bf86c to your computer and use it in GitHub Desktop.
Save cs-fedy/f9e495f1f714a00e62a07713285bf86c to your computer and use it in GitHub Desktop.
fill file with user input using posix in c.
#include <unistd.h>
#include <fcntl.h>
#define size 100
int main() {
// This program creates a file where it copies the
//data read from the keyboard.
int file, nb_char;
char buffer[size];
// create, open file
file = open("file.txt", O_CREAT | O_WRONLY | O_TRUNC);
if (file == -1) {
write(2, "error while opening file.txt \n", 20);
return -1;
}
write(1, "file.txt opened!! \n", 23);
// get and write user input in file.txt
while (nb_char = read(0, buffer, size) > 0) {
if (write(file, buffer, nb_char) == -1) {
return -1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment