我试图写入文件,然后将该文件的内容存储在变量中,这是我的代码:
#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;
}
当我执行该脚本时,我输入密码后会给我Segmentation Fault
。我们说我的序列号为1866203214226041
,因此/tmp/file.txt
应包含:
Serial Number: 1866203214226041
变量serial_number
应为:1866203214226041
我该如何解决?