【问题标题】:Printing a Linked List to existing Text file- Overwriting the File将链接列表打印到现有文本文件 - 覆盖文件
【发布时间】:2015-04-30 17:09:59
【问题描述】:

大家好,我发现很难找到一种将链表写入现有文本文件的方法。在程序开始时,我从文本文件中读取员工数据并将它们存储在链表中。然后用户可以添加员工。在程序结束时,链表被写入文件,在程序下次加载时更新它。这是我到目前为止所拥有的。任何帮助表示赞赏。

这是我的代码

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


#define ID_LENGTH 25
#define NAME_LENGTH 25
#define address_LENGTH 25
#define department_LENGTH 25
#define joinDate_LENGTH 25
#define email_LENGTH 30
int mymenu;

//Create employee Structure
typedef struct employee{
	char* ID;
	char* name;
	char* department;
	char* address;
	char* joinDate;
	double salary;
	char* email;
	struct employee *next;
}employee;

//Declare Function Prototypes
int login();
int Menu();
void Add(struct employee *head);
void search(struct employee *head, char*);
void WriteListToFile(employee *head);
void update(struct employee *head, char*);
void outputList();
struct employee* searchForEmployee(char* );
void savetxt(struct employee *head);
employee* new_employee(char*, char*, char*, char*, char*, double, char*);
employee* insert_by_employee(employee*, employee*);
void removeEmployee(char *);
void print_list(employee*); // prints out the LinkedList


employee* head = NULL; 
employee* tail = NULL;
employee* temp = NULL;
employee* current = NULL;


//this stores the employee that comes before the employee that is found by the searchforEmployee
struct employee *empBeforeEmptoDelete = NULL;

int main() {
	int num = 0;


	FILE *in;
	char* ID = (char*)malloc(sizeof(char*) * ID_LENGTH);
	char* name = (char*)malloc(sizeof(char*) * NAME_LENGTH);
	char* department = (char*)malloc(sizeof(char*) * department_LENGTH);
	char* address = (char*)malloc(sizeof(char*) * address_LENGTH);
	char* joinDate = (char*)malloc(sizeof(char*) * joinDate_LENGTH);
	double salary = 0;
	char* email = (char*)malloc(sizeof(char*) * email_LENGTH);

	
	if ((in = fopen("Employees.txt", "r")) == NULL) //Did the file successfully open?
	{
		printf("The input file failed to open.\n");
		printf("Program cannot continue. Exiting. . .\n");
		return 1; //Exit Program
	}


	while (!feof(in)) //Check for file end
	{
		//Read first data value to kickstart.
		if (fscanf(in, "%s %s %s %s %s %lf %s", ID, name, department, address, joinDate, &salary, email) == EOF) {
			break;
		}

		employee* hold = new_employee(ID, name, department, address, joinDate, salary, email);
		head = insert_by_employee(head, hold);

	}
	login();
	
}
employee* new_employee(char* id, char* name, char* department, char* address, char* joinDate, double salary, char* email) {

	//Create new employee and malloc space
	employee* new = (employee*)malloc(sizeof(struct employee));
	new->ID = (char*)malloc(sizeof(char) * ID_LENGTH);
	new->name = (char*)malloc(sizeof(char) * NAME_LENGTH);
	new->department = (char*)malloc(sizeof(char) * department_LENGTH);
	new->address = (char*)malloc(sizeof(char) * address_LENGTH);
	new->joinDate = (char*)malloc(sizeof(char) * joinDate_LENGTH);
	new->email = (char*)malloc(sizeof(char) * email_LENGTH);
	


	//Set data
	strcpy(new->ID, id);
	strcpy(new->name, name);
	strcpy(new->department, department);
	strcpy(new->address, address);
	strcpy(new->joinDate, joinDate);
	new->salary = salary;
	strcpy(new->email, email);
	//Retun a pointer to the node
	return new;

}

//Inserts new node into an alphabetically sorted linked list.
employee* insert_by_employee(employee* head, employee* new)
{
	employee* current = NULL;
	current = head;
	if (current == NULL || strcmp(current->department, new->department) > 0)
	{
		new->next = current;
		return new;
	}
	else {

		while (current->next != NULL && strcmp(current->next->department, new->department) < 0)
		{

			current = current->next;
		}
	}
	new->next = current->next;
	current->next = new;
	return head;

}
struct employee* searchForEmployee(char* id){
	struct employee *empIterator = head;
	char i[] = "Employee ID";
	char n[] = "Name";
	char a[] = "Address";
	char d[] = "Department";
	char jd[] = "Join Date";
	char s[] = "Salary";
	char em[] = "Email";

	while (empIterator != NULL){
		int isEqual = strcmp(empIterator->ID, id);//if the passed in ID is equla to the ID of the node then isEqual will ring true

		if (!isEqual){
		
			printf("Employee Found\n");
			printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
			printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", empIterator->ID, empIterator->name, empIterator->address, empIterator->department, empIterator->joinDate, empIterator->salary, empIterator->email);
			//printing out the current node which is the desired employee
			printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");
			return empIterator;
		}
		empBeforeEmptoDelete = empIterator;

		empIterator = empIterator->next;
	}
	printf("%s was not found\n\n", id);
	return NULL;
}
void print_list(employee* head)
{
	employee* current;
	current = head;
	char i[] = "Employee ID";
	char n[] = "Name";
	char a[] = "Address";
	char d[] = "Department";
	char jd[] = "Join Date";
	char s[] = "Salary";
	char em[] = "Email";
	

	//Header
	printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);
	printf("--------------------------------------------------------------------------------------------------------------------------------------------\n");


	while (current != NULL)
	{
		printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", current->ID, current->name, current->address, current->department, current->joinDate, current->salary, current->email);
		current = current->next;
	}
	printf("-------------------------------------------------------------------------------------------------------------------------------------------\n");
	
	
	return;
}
//login function takes in user input and compares it the 3
//entries in the Login Struct
int login()
{
	char ch;
	char username[7];//holds the username
	char password[7];//holds the password
	int i;

	printf("\nPlease enter your Username: ");
	gets(username);
	printf("\nPlease enter your Password: ");
	for (i = 0; i<4; i++)//loop 4 times
	{
		ch = getch();//get the first character entered for password
		password[i] = ch;//insert it into the password array
		ch = '*';//change the value of ch to '*'
		printf("%c", ch);//print ch which now contains '*' to the screen
	}

	password[i] = '\0';

	struct login{
		char name[7];
		char password[7];

	};
	struct login details[3];
	fflush(stdin);

	FILE *file;
	file = fopen("login.txt", "r");
	if (file == NULL){
		printf("Can not open the file\n");
		exit(-1);
	}
	fflush(stdin);

	for (int i = 0; i < 3; i++){
		fscanf(file, "%s %s\n", details[i].name, details[i].password);
	}


	for (int i = 0; i < 3; i++){
		if ((strcmp(details[i].name, username) == 0) && (strcmp(details[i].password, password) == 0))
		{
			printf("\nWelcome %s\n", username);
			Menu();
		}
		fflush(stdin);
	}
}
////basic menu function with a switch statement
int Menu()
{
	int menuChoice = 0;
	int Choice = 9;

	while(menuChoice != 8 ){

		printf("\n");
		printf("1. Add\n");
		printf("2. Show\n");
		printf("3. Update\n");
		printf("4. Delete\n"); // Write a Function for this
		printf("5. Departments\n");
		printf("6. Employee Report\n");
		printf("7. \n");
		printf("8. Exit\n\n\n\t\tSELECTION = ");
		fflush(stdin);
		scanf("%d", &Choice);
		fflush(stdin);

		
			switch (Choice)
			{
			case 1:
			{
				Add(head);
				break;
			}
			case 2:
			{
				char text[10];
				printf("Enter the text to search for :");
				scanf("%s", text);
				//search(head, text);
				searchForEmployee(text);
				break;
			}
			case 3:
			{
				char text[10];
				printf("Enter the ID to update for :");
				scanf("%s", text);
				update(head, text);
				break;
			}
			case 4:
			{
				print_list(head);
				char text[10];
				printf("Enter the ID to remove :");
				scanf("%s", text);
				removeEmployee(text);
				print_list(head);
				break;

			}
			case 5:
			{
				print_list(head);
				break;
			}
			case 6:
			{

				break;
			}
			case 7:
			{
				break;
			}
			case 8:
			{
				WriteListToFile(head);
				exit(0);
				break;
			}
			default:
			{
				printf("\nInvalid Selection");
				break;
			}
			}
		}
		system("Pause");
		printf("\n\n\n");
		return 1; //Exit Success
	} 
//my add function which validates the email and start date
void Add()
{
	
	char* ID = (char*)malloc(sizeof(char*) * ID_LENGTH);
	char* name = (char*)malloc(sizeof(char*) * NAME_LENGTH);
	char* department = (char*)malloc(sizeof(char*) * department_LENGTH);
	char* address = (char*)malloc(sizeof(char*) * address_LENGTH);
	char* joinDate = (char*)malloc(sizeof(char*) * joinDate_LENGTH);
	char* tempDate = (char*)malloc(sizeof(char*) * joinDate_LENGTH);
	double salary = 0;
	char* email = (char*)malloc(sizeof(char*) * email_LENGTH);
	char temp[25];
	char com[5] = ".com";
	int m, d, y;
	int daysinmonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int legit = 3;

	printf("\nEnter the ID : ");
	scanf("%s", ID);
	printf("\nEnter the new employee name : ");
	scanf("%s", name);
	printf("\nEnter their address : ");
	scanf("%s", address);
	printf("\nEnter their department : ");
	scanf("%s", department);
	while (legit != 1){
	printf("\nEnter their start date : ");
	scanf("%s", tempDate);
	sscanf(tempDate, "%02d/%02d/%04d", &m, &d, &y);
	//printf("%d%d%d",m,d,y);
	
		// leap year checking, if ok add 29 days to february
		if (y % 400 == 0 || (y % 100 != 0 && y % 4 == 0))
			daysinmonth[1] = 29;

		// days in month checking
		if (m < 13)
		{
			if (d <= daysinmonth[m - 1])
				legit = 1;
		}

		if (legit == 1){
			printf("\nIt is a legitimate date!\n");
			strcpy(joinDate, tempDate);
		}
		else
			printf("\nIt's not a legitimate date!");
	}
	printf("\nEnter their salary : ");
	scanf("%lf", &salary);
	printf("\nEnter their email : ");
	scanf("%s", temp);
	printf(temp);
	//I use strchr to check the input for a single '@'
	//I then use strstr to check for a substring
	 while (strchr(temp, '@') == NULL || strstr(temp, com) == NULL)
	 {
		printf("\nThe email doesnt contain an @ sign or .com .");
		printf("\nEnter Employee E-Mail: ");
		fflush(stdin);
		gets(temp);
	}
	strcpy(email, temp);
	
	employee* hold = new_employee(ID, name, department, address, joinDate, salary, email);
	head = insert_by_employee(head, hold);
}
//search by ID or name
void search(struct employee *head, char *crit)//This function takes in the head pointer and a character array pointer
{
	int choice;//menu choice tracker

	//arrays to hold the header heads
	char i[] = "Employee ID";
	char n[] = "Name";
	char a[] = "Address";
	char d[] = "Department";
	char jd[] = "Join Date";
	char s[] = "Salary";
	char em[] = "Email";

	//sub menu to filter by ID and Name searches
	printf("\nSearch by ");
	printf("\n1 : ID");
	printf("\n2 : Name\n");
	scanf("%d", &choice);

	//if the user wants to search by ID
	if (choice == 1){
		while (head != NULL)
		{
			//compare the ID to the criteria. If its the same then execute this if
			if ((strcmp(head->ID, crit) == 0))
			{
				//print that we found the employee
				printf("Employee Found\n");
				printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
				printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", head->ID, head->name, head->address, head->department, head->joinDate, head->salary, head->email);
				//printing out the current node which is the desired employee
				printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				return;
			}
			head = head->next;//increments the node until we get to the end of the Linked List
		}
		printf("Employee not found\n");//Else there is no Employee with an ID of the entered criteria
	}
	//if the user wants to search by Name
	else if (choice == 2){
		while (head != NULL)
		{
			//compare the Name to the criteria. If its the same then execute this if
			if ((strcmp(head->name, crit) == 0))
			{
				//print that we found the employee
				printf("Employee Found\n");
				printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
				printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", head->ID, head->name, head->address, head->department, head->joinDate, head->salary, head->email);
				//printing out the current node which is the desired employee
				printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				return;
			}
			head = head->next;//increments the node until we get to the end of the Linked List
		}
		printf("Employee not found\n");//Else there is no Employee with an Name of the entered criteria
	}
	else
		printf("Bad input");//Otherwise the user entered a choice out of the range of our handled input
}
//the update function uses the search function then uses a holder to transfer data and then overwrite it
void update(struct employee *head, char *crit)//This function takes in the head pointer and a character array pointer
{


	//arrays to hold the header heads
	char i[] = "Employee ID";
	char n[] = "Name";
	char a[] = "Address";
	char d[] = "Department";
	char jd[] = "Join Date";
	char s[] = "Salary";
	char em[] = "Email";

	char id[25];
	char name[25];
	char address[25];
	char department[25];
	char joinDate[25];
	double salary;
	char email[25];

	
	//if the user wants to search by ID
		while (head != NULL)
		{
			//compare the ID to the criteria. If its the same then execute this if
			if ((strcmp(head->ID, crit) == 0))
			{
				//print that we found the employee
				printf("Employee Found\n");
				printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
				printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", head->ID, head->name, head->address, head->department, head->joinDate, head->salary, head->email);
				//printing out the current node which is the desired employee
				printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");

				printf("\nEnter the ID : ");
				scanf("%s", id);
				printf("\nEnter the new employee name : ");
				scanf("%s", name);
				printf("\nEnter their address : ");
				scanf("%s", address);
				printf("\nEnter their department : ");
				scanf("%s", department);
				printf("\nEnter their start date : ");
				scanf("%s", joinDate);
				printf("\nEnter their salary : ");
				scanf("%lf", &salary);
				printf("\nEnter their email : ");
				scanf("%s", email);

				strcpy(head->ID, id);
				strcpy(head->name, name);
				strcpy(head->department, department);
				strcpy(head->address, address);
				strcpy(head->joinDate, joinDate);
				head->salary = salary;
				strcpy(head->email, email);

				printf("Employee Found\n");
				printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
				printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
				printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", head->ID, head->name, head->address, head->department, head->joinDate, head->salary, head->email);
				//printing out the current node which is the desired employee
				printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");

				return;
			}
			head = head->next;//increments the node until we get to the end of the Linked List
		}
		printf("Employee not found\n");//Else there is no Employee with an ID of the entered criteria
	}
//this was a secondary function to output the LinkedList. Not the one used in finished solution
void outputList(){
	//this was a secondary function to output the LinkedList. Not the one used in finished solution
	char i[] = "Employee ID";
	char n[] = "Name";
	char a[] = "Address";
	char d[] = "Department";
	char jd[] = "Join Date";
	char s[] = "Salary";
	char em[] = "Email";

	struct employee * employees = head;
	printf("Employees Entered\n\n");
	while (employees != NULL){
		printf("Employee Found\n");
		printf("\n\n|%15s | %15s | %15s | %15s | %15s| %15s | %15s|\n", i, n, a, d, jd, s, em);//header formatting
		printf("|%15s | %15s | %15s |%15s | %15s | %15.2lf| %25s\n", employees->ID, employees->name, employees->address, employees->department, employees->joinDate, employees->salary, employees->email);
		printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");

		employees = employees->next;
	}
}//this was a secondary function to output the LinkedList. Not the one used in finished solution
//my remove employee function
void removeEmployee(char* empID){

	struct employee* empToDelete = NULL;//this holds the employee we are deleting

	empToDelete = searchForEmployee(empID);//we use the search function we made to get the employees details

	if (empToDelete != NULL){//if we find him execute this for

		printf("%s was deleted\n\n", empID);//let the user know the employee details ahve been deleted

		if (empToDelete == head){

			head = empToDelete->next;
		}
		else{
			empBeforeEmptoDelete->next = empToDelete->next;
		}

		free(empToDelete);//Delete the details from memory
	}
	else//otherwise the employee was not found
	{
		printf("%s was not found", empID);
	}
}
void savetxt(struct employee *head)
{
	FILE *f;
	f = fopen("Employees.txt", "w+");
	if (f == NULL)
	{
		printf("error");
	}
	//struct employee *Current = head->next;
	while (head != NULL)
	{
		
		fprintf(f, "%s\n", head->ID);
		fprintf(f, "%s\n", head->name);
		fprintf(f, "%s\n", head->address);
		fprintf(f, "%s\n", head->department);
		fprintf(f, "%s\n", head->joinDate);
		fprintf(f, "%lf\n", head->salary);
		fprintf(f, "%s\n", head->email);
		head = head->next;
	}
		//head = head->next;
		fprintf(f, "\n\n");
	
	fclose(f);
	return NULL;
}

void WriteListToFile(employee *head) {
	FILE *pFile;
	pFile = fopen("Employees.txt", "w");

	if (pFile != NULL) {
		employee *currentEmp = head;

		employee *holdNext = NULL;
		

		while (currentEmp != NULL) {
			holdNext = currentEmp->next;
			
			currentEmp->next = NULL;

			fseek(pFile, 0, SEEK_END);
			fprintf(currentEmp, sizeof(employee), 1, pFile);

			printf("Writing:%s to file\n", currentEmp->name);

			currentEmp->next = holdNext;

			holdNext = NULL;
			currentEmp = currentEmp->next;
		}
		fclose(pFile);
		pFile = NULL;
	}
	else {
		printf("FILE OPEN ERROR\n");
	}

}
这是员工文本文件
EMP1 Martin Computer Clare 06/06/1996 60000 martinemp@gmail.com
EMP2 John Accounting Galway 05/05/1995 50000 johnemp@gmail.com
EMP3 Kevin Computer Kilkenny 04/04/1994 34000 kevinemp@gmail.com
EMP4 Kim Sales Sligo  03/03/1993 65000 kimemp@gmail.com
EMP5 Keith Accounting Ballina 02/02/1992 53200 keithemp@gmail.com
EMP6 Tim Sales Dublin 01/01/1991 23000 timemp@gmail.com
EMP7 Andy Computer Chicago 07/07/1990 10000 andyemp@gmail.com

这是登录信息

martin 1234
tim 5678
keith 4321

【问题讨论】:

  • 您看到了什么问题?
  • 嘿嘿基本上程序结束时文件是空的。
  • 所以链接列表可能是空的?你看到标准输出上的“try”行了吗?这些字段也可能是空字符串。也打印出来。
  • 我有一个功能可以将链表打印到屏幕上。不是空的
  • 如果将所有fprintfs 更改为printfstdout,是否打印?

标签: c file-io linked-list nodes


【解决方案1】:

编辑 1:

问题似乎在这里:

if (f == NULL)
{
    printf("error");
}

即使您正在测试 NULL,您也不会立即退出该方法。

if (f == NULL)
{
    printf("error");
    return;
}

初步建议(暂时忽略):

您可以在删除下一个head 移动后尝试吗?它应该会抛出错误。

void savetxt(struct employee *head)
{
	FILE *f;
	f = fopen("Employees.txt", "w+");
	if (f == NULL)
	{
		printf("error");
	}
	struct employee *Current = head->next;
	while (head != NULL)
	{
		
		printf("try");
		fprintf(f, "%s\n", head->ID);
		fprintf(f, "%s\n", head->name);
		fprintf(f, "%s\n", head->address);
		fprintf(f, "%s\n", head->department);
		fprintf(f, "%s\n", head->joinDate);
		fprintf(f, "%lf\n", head->salary);
		fprintf(f, "%s\n", head->email);
		head = head->next;
	}
		/* head = head->next; */
		fprintf(f, "\n\n");
	
	fclose(f);
	return NULL;
}

【讨论】:

  • LinkedList.exe 中 0x7706CC70 (ntdll.dll) 处的第一次机会异常:0xC0000008:指定了无效句柄。它向我抛出了这个错误。
猜你喜欢
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 2016-04-22
  • 1970-01-01
  • 2013-07-12
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多