Added helper function to read file into string

master
Aadhavan Srinivasan 2 years ago
parent b4140c5888
commit c0c567c7ae

@ -1,25 +1,63 @@
#include "message.h" #include "message.h"
#include "user.h" #include "user.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int num_of_lines(char* filename);
char* file_to_string(char* filename);
int main() {
User[num_of_lines("user_file.txt")] users; int main() {
FILE* fp = fopen("user_file.txt", "w+"); int num_users = num_of_lines("user_file.txt");
/* Structure of user file - <username> <password> on every line */
char* file_str = file_to_string("user_file.txt");
char* token = malloc(sizeof(char) * 30);
User users[num_users];
token = strtok(file_str," \r\n");
Message message = new_message("Hello, this is a text message",user1,user2); 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");
}
Message message = new_message("Hello, this is a text message",users[0],users[1]);
printf("Message was: %s\nSentfrom: %s\nSent to: %s\nSent at: %s\n",message.text,message.sender.username,message.recipient.username,asctime(&message.timeinfo)); printf("Message was: %s\nSentfrom: %s\nSent to: %s\nSent at: %s\n",message.text,message.sender.username,message.recipient.username,asctime(&message.timeinfo));
}
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 /* Finds the number of lines in a file (Which MUST end in a new-line, if the last
line is to be counted) */ line is to be counted) */

Loading…
Cancel
Save