Лекция 21 - Файлов вход/изход част 2
// files.c
#include <stdio.h>
int main() {
FILE* my_file;
my_file = fopen("./out.txt", "a"); // w a
if(my_file != NULL) {
// scanf
// gets, fgets
// getc, getchar
// fscanf
// fgets
// fgetc
/*for(int i=0; i<100;i++) {
char c = fgetc(my_file);
printf("c = \"%c\"\n", c);
}*/
/* c = fgetc(my_file);
printf("c = \"%c\"\n", c);
c = fgetc(my_file);
printf("c = \"%c\"\n", c);
c = fgetc(my_file);
printf("c = \"%c\"\n", c);*/
/*for(;;) {
char c = fgetc(my_file);
if(c != EOF) {
putchar(c);
//printf("%d", c);
} else {
puts("\nfile end has been reached\n");
break;
}
}*/
/*for(;;) {
char c[10];
if(fgets(c, 10, my_file) != NULL) {
// puts(c);
printf("%s", c);
} else {
puts("\nfile end has been reached\n");
break;
}
}*/
/*char str[10];
int num;
float fraction;
for(;;) {
if(fscanf(my_file, "%s%d%f", str, &num, &fraction) == EOF) {
break;
}
printf("Read: %s %d %f\n", str, num, fraction);
}*/
// fputc
// fputs
// fprintf
if(fputc('c', my_file) == EOF) {
puts("ERROR WRITING TO FILE!");
}
fputc('\n', my_file);
//fprintf(my_file, "%c", '\n');
fputs("I AM GROOT\n", my_file);
fprintf(my_file, "%s %d\n", "Hello", 123);
fclose(my_file);
} else {
printf("Failed to open file!\n");
}
return 0;
}
// test.txt
Hello 123 123.456
Goodbye 789 789.123
// files2.c
#include <stdio.h>
int main() {
FILE* outFile;
FILE* logFile;
outFile = fopen("out2.txt", "w");
logFile = fopen("log.txt", "a");
if(outFile != NULL && logFile != NULL) {
char str[10];
while(fgets(str, 10, stdin) != NULL) {
fputs(str, outFile);
fputc('\n', outFile);
fprintf(logFile, "Read name: %s\n", str);
}
fclose(outFile);
fclose(logFile);
}
return 0;
}
// files3.c
#include <stdio.h>
struct person_t {
char first_name[15];
unsigned int age;
char last_name[15];
};
int main() {
FILE* outFile;
outFile = fopen("out3.txt", "r");
if(outFile != NULL) {
/*for(int i=10000; i<10005; i++) {
//fprintf(outFile, "%d\n", i);
fwrite(&i, sizeof(int), 1, outFile);
}*/
/*for(;;) {
int i;
fread(&i, sizeof(int), 1, outFile);
if(feof(outFile)) {
break;
}
//fread(&i, sizeof(int), 1, outFile);
printf("Read: %d\n", i);
}*/
//struct person_t pers = {"Hello", 19, "Godbye"};
//fwrite(&pers, sizeof(struct person_t), 1, outFile);
struct person_t pers;
fread(&pers, sizeof(struct person_t), 1, outFile);
printf("%s %s %d\n", pers.first_name, pers.last_name, pers.age);
fclose(outFile);
}
return 0;
}