You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.8 KiB
C

2 years ago
#include "message.h"
#include "user.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2 years ago
int num_of_lines(char* filename);
char* file_to_string(char* filename);
User* create_user_list(char* filename);
2 years ago
int main() {
2 years ago
User* users = create_user_list("user_file.txt");
Message message = new_message("Hello, this is a text message",users[0],users[1]);
printf("Message was: %s\nSentfrom: %s\nSent to: %s\nWith password: %s\nSent at: %s\n",message.text, message.sender.username, message.recipient.username, message.recipient.password, asctime(&message.timeinfo));
2 years ago
}
2 years ago
User* create_user_list(char* filename) {
/* Structure of user file - <username> <password> on every line */
int num_users = num_of_lines(filename);
char* file_str = file_to_string(filename);
char* token = malloc(sizeof(char) * 30);
User* users = calloc(num_users, sizeof(User));
token = strtok(file_str," \r\n");
for (int i=0;i<num_users;i++) {
users[i].username = token;
token = strtok(NULL," \r\n");
users[i].password = token;
token = strtok(NULL," \r\n");
}
return users;
}
2 years ago
char* file_to_string(char* filename) {
FILE* fp = fopen(filename,"r");
fseek(fp,0,SEEK_END);
long file_size = ftell(fp);
rewind(fp);
char* buffer = calloc(sizeof(char),file_size+1);
fread(buffer,1,file_size,fp);
fclose(fp);
return buffer;
2 years ago
}
2 years ago
/* Finds the number of lines in a file (Which MUST end in a new-line, if the last
line is to be counted) */
int num_of_lines(char* filename) {
int num_lines = 0;
FILE* fp = fopen(filename,"r");
if (fp == NULL) {
return -1;
}
for (int c = getc(fp); c != EOF; c = getc(fp)) {
if (c == '\n') {
num_lines++;
}
}
fclose(fp);
return num_lines;
}