From ec40022c5082616b0ad59422530ac1270af0507d Mon Sep 17 00:00:00 2001 From: TomatenMarc <marc.feger@uni-duesseldorf.de> Date: Tue, 22 May 2018 21:56:17 +0200 Subject: [PATCH] Add File Handling Exampler. --- Open_Close_Read_Write/file_handling.c | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Open_Close_Read_Write/file_handling.c diff --git a/Open_Close_Read_Write/file_handling.c b/Open_Close_Read_Write/file_handling.c new file mode 100644 index 0000000..00056d1 --- /dev/null +++ b/Open_Close_Read_Write/file_handling.c @@ -0,0 +1,46 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <string.h> + +int main(void){ + + int FLAG = O_RDONLY; + int file = open("/proc/cpuinfo", FLAG); + + int size = 1000; + char *buffer = malloc(size * sizeof(char)); + if(read(file, buffer, size) == -1){ + perror("read error"); + free(buffer); + return -1; + } + + char var_name[size]; + char var_value[size]; + sscanf(buffer, "%*s %*s %*s %s %*s %s", var_name, var_value); + + printf("%s: %s\n", var_name, var_value); + + int FLAG2 = O_WRONLY; + int FLAG3 = O_CREAT; + int FLAG4 = O_APPEND; + int file2 = open("output.txt", FLAG2 | FLAG3 | FLAG4); + + char *msg = "Hallo Welt\n"; + + + if(write(file2, msg, strlen(msg)) == -1){ + perror("write error"); + return -1; + } + + + free(buffer); + close(file); + close(file2); + return 0; +} -- GitLab