I'm trying to write to a file and then store the content of that file in a variable, here's my code:
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(){
char *input;
char *line;
char *sn;
char *serial_number;
char* key = "Serial Number";
printf("Password:\n");
scanf("%s", input);
if (!strcmp(input, "mypassword")){
// Write a serial number to a file
printf("Serial Number:\n");
scanf("%s", sn);
FILE *f = fopen("/tmp/file.txt", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
fprintf(f,"Serial Number: %s", sn);
fclose(f);
// Store the serial number from a file in a variable
FILE *file = fopen("/tmp/file.txt", "r");
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
//fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
serial_number = strdup(value);
break; // once the key has been found we can stop reading
}
}
fclose(file);
printf("Your hardware serial number is: %s\n", serial_number);
}
else {
printf("Wrong password\n");
}
return 0;
}
When I execute that script, it gives me Segmentation Fault
after I put in my password. Let's say my serial number is 1866203214226041
so /tmp/file.txt
should contain:
Serial Number: 1866203214226041
And the variable serial_number
should be: 1866203214226041
How should I fix it ?