Запись и считывание файла - выводится мусор - C (СИ)
Формулировка задачи:
Запись проходит нормально, но при чтении машина подтягивает мусор из оперативки, в чем проблема?
#include <stdio.h>
#include <stdlib.h>
#include <sys\stat.h>
#include <io.h>
#include <fcntl.h>
#include <ctype.h>
#include <windows.h>
#include <string.h>
struct train
{
char place[15];
char num[15];
char depTime[15];
};
int main()
{
int i, c,a,b;
train trains[5];
train trains1[5];
FILE *tPtr;
FILE *t1Ptr;
int f1 = 0;
train swap;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
tPtr = fopen("trains.dat", "w");
if (tPtr == NULL)
printf("open failed on input file\n");
else
{
printf("Введіть дані про 5 потягів\n\n");
for (i = 0; i < 5; i++)
{
printf("Пункт призначення потягу: ");
scanf("%s", trains[i].place);
printf("Введіть номер потягу: ");
scanf("%s", trains[i].num);
printf("Введіть час відправлення(в годинах): ");
scanf("%s", trains[i].depTime);
fprintf(tPtr, "%s %s %s\n", trains[i].place, trains[i].num, trains[i].depTime);
}
fclose(tPtr);
}
t1Ptr = fopen("trains.dat", "r");
if (t1Ptr == NULL)
perror("file cannot be open\n");
else
{
for (i = 0; i < 5; i++)
{
fscanf(t1Ptr, "%s %s %s", &trains[i].place, &trains[i].num, &trains[i].depTime);
if (feof(t1Ptr))
break;
}
fclose(t1Ptr);
}
for (i = 0; i < 1; i++)
{
printf("%-10s\t", trains1[i].place);
printf("%-10s\t", trains1[i].num);
printf("%-10s\n", trains1[i].depTime);
}
printf("\n");
system("pause");
return 0;
}Решение задачи: «Запись и считывание файла - выводится мусор»
textual
Листинг программы
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
typedef struct
{
char place[15];
char num[15];
char depTime[15];
}train;
int main()
{
int i;
train trains[5];
train trains1;
FILE *tPtr;
FILE *t1Ptr;
int f1 = 0;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
tPtr = fopen("trains.dat", "w");
if (tPtr == NULL)
printf("open failed on input file\n");
else
{
printf("Введіть дані про 5 потягів\n\n");
for (i = 0; i < 5; i++)
{
printf("Пункт призначення потягу: ");
scanf("%s", trains[i].place);
printf("Введіть номер потягу: ");
scanf("%s", trains[i].num);
printf("Введіть час відправлення(в годинах): ");
scanf("%s", trains[i].depTime);
fprintf(tPtr, "%s %s %s\n", trains[i].place, trains[i].num, trains[i].depTime);
}
fclose(tPtr);
}
puts("");
t1Ptr = fopen("trains.dat", "r");
if (t1Ptr == NULL)
perror("file cannot be open\n");
else
{
while (!feof(t1Ptr))
{
fscanf(t1Ptr, "%s %s %s\n", trains1.place, trains1.num, trains1.depTime);
printf("Place: %s\tNum= %s\tdepTime= %s\n", trains1.place, trains1.num, trains1.depTime);
}
fclose(t1Ptr);
}
puts("");
system("pause");
return 0;
}