workbench: Created files_handling stub
This commit is contained in:
parent
dec747efc1
commit
d238fe03b8
88
workbench/files_handling/main.c
Normal file
88
workbench/files_handling/main.c
Normal file
@ -0,0 +1,88 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define BUFFER_SIZE 256
|
||||
|
||||
void create_file(const char *filename) {
|
||||
FILE *file = fopen(filename, "w");
|
||||
if (file == NULL) {
|
||||
printf("Error creating file: %s\n", filename);
|
||||
exit(1);
|
||||
}
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
void write_to_file(const char *filename, const char *content) {
|
||||
FILE *file = fopen(filename, "w");
|
||||
if (file == NULL) {
|
||||
printf("Error opening file: %s\n", filename);
|
||||
exit(1);
|
||||
}
|
||||
fputs(content, file);
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
void read_from_file(const char *filename) {
|
||||
FILE *file = fopen(filename, "r");
|
||||
if (file == NULL) {
|
||||
printf("Error opening file: %s\n", filename);
|
||||
exit(1);
|
||||
}
|
||||
char ch;
|
||||
while ((ch = fgetc(file)) != EOF) {
|
||||
putchar(ch);
|
||||
}
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
void append_to_file(const char *filename, const char *content) {
|
||||
FILE *file = fopen(filename, "a");
|
||||
if (file == NULL) {
|
||||
printf("Error opening file: %s\n", filename);
|
||||
exit(1);
|
||||
}
|
||||
fputs(content, file);
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
void delete_file(const char *filename) {
|
||||
if (remove(filename) != 0) {
|
||||
printf("Error deleting file: %s\n", filename);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
char filename[BUFFER_SIZE];
|
||||
char input_buffer[BUFFER_SIZE];
|
||||
|
||||
memset(filename, 0, BUFFER_SIZE);
|
||||
memset(input_buffer, 0, BUFFER_SIZE);
|
||||
|
||||
printf("Enter the filename: ");
|
||||
|
||||
// last byte can be non-zero -> leak
|
||||
fgets(filename, BUFFER_SIZE, stdin);
|
||||
|
||||
create_file(filename);
|
||||
|
||||
printf("Enter content to write to the file: ");
|
||||
fgets(input_buffer, BUFFER_SIZE, stdin);
|
||||
write_to_file(filename, input_buffer);
|
||||
|
||||
printf("Content of the file:\n");
|
||||
read_from_file(filename);
|
||||
|
||||
printf("\nEnter content to append to the file: ");
|
||||
fgets(input_buffer, BUFFER_SIZE, stdin);
|
||||
append_to_file(filename, input_buffer);
|
||||
|
||||
printf("\nContent of the file after appending:\n");
|
||||
read_from_file(filename);
|
||||
|
||||
delete_file(filename);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user