Untitled
unknown
plain_text
2 years ago
2.1 kB
9
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char filePathGlobal[256] = ""; // Глобальная переменная для хранения пути к файлу
void readFile(const char *filePath) {
FILE *file = fopen(filePath, "r");
if (file == NULL) {
printf("n/a\n");
return;
}
char ch;
int isEmpty = 1;
while ((ch = fgetc(file)) != EOF) {
isEmpty = 0;
putchar(ch);
}
fclose(file);
if (isEmpty) {
printf("n/a\n");
}
printf("\n"); // Перенос строки после вывода содержимого файла
}
void appendToFile(const char *filePath) {
printf("Enter text to append (text will be saved and displayed when exiting with -1): ");
scanf("%s", filePathGlobal); // Используйте fgets для ввода текста с пробелами, предварительно очистив буфер
FILE *file = fopen(filePath, "a");
if (file == NULL) {
printf("n/a\n");
return;
}
fprintf(file, "%s\n", filePathGlobal);
fclose(file);
}
int main() {
while (1) {
printf("1. Enter file path\n");
printf("2. Append text to file\n");
printf("-1. Exit and display file content\n");
printf("Choose an option: ");
int choice;
scanf("%d", &choice);
if (choice == -1) {
if (strlen(filePathGlobal) != 0) {
readFile(filePathGlobal);
} else {
printf("n/a\n");
}
break;
}
switch (choice) {
case 1: {
printf("Enter file path: ");
scanf("%s", filePathGlobal);
break;
}
case 2: {
if (strlen(filePathGlobal) == 0) {
printf("n/a\n");
} else {
appendToFile(filePathGlobal);
}
break;
}
default:
printf("n/a\n");
break;
}
}
return 0;
}
Editor is loading...
Leave a Comment