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
91 lines
1.8 KiB
C
#include "message.h"
|
|
#include "user.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
int num_of_lines(char* filename);
|
|
char* file_to_string(char* filename);
|
|
User* create_user_list(char* filename);
|
|
|
|
int main() {
|
|
|
|
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));
|
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* 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;
|
|
|
|
}
|