Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 18.12.2019, 03:24   #1
Denton72
Пользователь
 
Регистрация: 11.10.2015
Сообщений: 25
Плохо Построение с таблицой в бинаром файлом

*Показывает данные (в табличном формате(массив)) из бинарного файла.
* Затем попросить пользователя ввести данные для заполнения
Таблица что то вроде

My kill list
-----------------------------------
No|FullName|Age|Reason to kill |
-----------------------------------
При этом учитывать пустые поля
* Сохраняя пользовательский ввод в файл(не переписывая файл но при это добавляю данные в конце старых данных)
иметь кнопку чтобы выйти и сохраниться
printf("слова слова(press # to save and close):\n");
while(1)
{
ch=getchar();
if(ch=='#')
{
break;
}
fputc(ch,fp);
}
fclose(fp);

*Если файл не существует, ничего не показывать.(Текстом)

fp = fopen("file.bin", "wb");
(if (fp==NULL) printf("Error there is noting there");
getch();
exit(ERROR_FILE_OPEN);
}

есть совет как это сделать экономно?
Denton72 вне форума Ответить с цитированием
Старый 18.12.2019, 04:13   #2
Denton72
Пользователь
 
Регистрация: 11.10.2015
Сообщений: 25
По умолчанию

Код:
набросок к массиву
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

struct student {
	char name[20];
	char lastname[20];
	unsigned int course;
	char ReasonToKill[20];

};

void data_input(struct student *data, int num)
{
	int idx = 0;

	while(num-- > 0){
		printf("Enter Name,Lastnamem, course(numbers only),ReasonToKill(press enter after each section Andrejs[Enter] Ivanovs[Enter] 2[Enter] Uglymot..[Enter]\n if more then one student this message will repeat: ");
		scanf("%s %s %d %s", (data + idx)->name,
					(data + idx)->lastname,
					&(data + idx)->course,
					(data + idx)->ReasonToKill);
		idx++;
	}
}

void data_show(struct student *data, int num)
{
	int idx = 0;

	printf("Name                |"
		" LastName            |"
		" Course |"
		" ReasonToKill     \n");
	while(num-- > 0){
		printf("%-20s| %-20s| %-7d| %-10s\n", (data + idx)->name,
					(data + idx)->lastname,
					(data + idx)->course,
					(data + idx)->ReasonToKill);
		idx++;
	}
}

int main ()
{
	int num;
	struct student *sp = NULL;

	printf("Please enter number of students to kill: ");
	scanf("%d", &num);
	sp = (struct student *)malloc(sizeof(struct student) * num);
	if (!sp) {
		printf("Memory allocation failed\n");
		return -1;
	}

	data_input(sp, num);
	data_show(sp, num);

	free(sp);


	return 0;
}
Denton72 вне форума Ответить с цитированием
Старый 18.12.2019, 04:31   #3
Denton72
Пользователь
 
Регистрация: 11.10.2015
Сообщений: 25
По умолчанию

Набросок к сохранению файла и открытие(чтение)
Код:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

struct student {
	int group;
	int kurss;
};

int main (int argc, char **argv)
{
	int fd;
	int bytes = 0;
	char *file = "data.bin";
	struct student data = { 
		(data + idx)->name,
(data + idx)->lastname,
(data + idx)->course,
(data + idx)->ReasonToKill   очень забытые знания
	};

	fd = open(file, O_CREAT | O_TRUNC | O_RDWR, 0000777);
	if (fd == -1) {
		printf("File open error: %i (%s)\n",
				errno, strerror(errno));
		return fd;
	}

	bytes = write(fd, &data, sizeof(data));
	if (bytes == -1) {
		printf("File write error: %i (%s)\n",
				errno, strerror(errno));
		close(fd);
		return bytes;
	}

	printf("Student data saved to %s (%i bytes)\n",
					file, bytes);
	close(fd);

	return 0;
}

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

struct student {
	int group;
	int kurss;
};

int main (int argc, char **argv)
{
	int fd;
	int err = 0;
	int bytes = 1;
	int count = 0;
	int idx = 0;
	char *file = "data.bin";
	struct student *data = NULL;
	struct student *tmp;

	fd = open(file, O_RDWR, 0000777);
	if (fd == -1) {
		printf("File open error: %i (%s)\n",
					errno, strerror(errno));
		return fd;
	}

	data = (struct student *)malloc(sizeof(struct student));

	while (bytes > 0) {
		bytes = read(fd, data + count, sizeof(struct student));
		if (bytes == -1) {
			printf("File read error: %i (%s)\n",
					errno, strerror(errno));
			close(fd);
			free(data);
			return errno;
		}

		if (!bytes)
			break;

		if (bytes < sizeof(struct student)) {
			printf("Error: read %i bytes out of %lu\n",
				    bytes, sizeof(struct student));
			close(fd);
			free(data);
			return errno;
		}
		count++;
		tmp = (struct student *)realloc(data,
				sizeof(struct student) * (count + 1));
		if (!tmp) {
			close(fd);
			free(data);
			return errno;
		}
		data = tmp;
	}

	printf("group\tkurss\n");
	while (count--){
		printf("%i\t%i\n", (data + idx)->group,
				(data + idx)->kurss);
		idx++;
	}
	printf("Read %i records from %s\n", idx, file);

	close(fd);
	free(data);

	return 0;
}
Denton72 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Проблема с таблицой html tArAntAykA_ HTML и CSS 0 05.02.2017 14:04
Объединение временной таблицы с таблицой бд chui БД в Delphi 4 22.11.2011 11:36
Сравнение данных ячеек с таблицой webstar Microsoft Office Excel 3 06.12.2009 12:16
Проблема с таблицой Nadjuha БД в Delphi 5 15.08.2008 09:43