我正在为某个程序编写C代码以模拟患者数据库。我设法编写了将患者添加到数据库并将信息保存到文本文件的代码。
下面关闭数据库的代码并将信息保存到文本文件的代码很正常:
FILE *close_file;
close_file = fopen(file_name, "w");
if (close_file == NULL){
printf("save information to file failed!\n");
fclose(close_file);
exit(EXIT_FAILURE);
}
fprintf(close_file, "%d\n", *num_of_structs);/*Enters the number of the
patient in the DB in the
beginning of the text file*/
for (int j = 0; j < *num_of_structs;j++){
/*the for loop down below is to write referens number to the patients x-
ray pictures, so the first two numbers in the text file belong to an array
of two rooms*/
for (int picture = 0; picture < 2; picture++){
fprintf(close_file, "%d ", patientRegister[j].pictures[picture]);
}
/*down below I write the personal number and the name of the patient to
the text file*/
fprintf(close_file, "%d %s", patientRegister[j].personal_number,
patientRegister[j].patient_name);
}
fclose(close_file);
}
文本文件如下所示: https://ibb.co/FKdx4vg
我的问题是如何从此文本文件读取?我尝试了很多代码,但没有成功。看到我的代码对我来说不起作用,除了以下行:
fscanf(existing_file, "%d", num_of_structs);/*This reads the first number
at the top of the text file and which represents the number of patients in
the DB*/
查看应该打开一个文本文件并从中读取的整个功能:
void open_existing_file(Patient patientRegister[], char file_name[], int
*num_of_structs) {
FILE *existing_file;
existing_file = fopen(file_name, "r");
if (existing_file == NULL) {
printf("Open existing file failed\n");
fclose(existing_file);
exit(EXIT_FAILURE);
}
fscanf(existing_file, "%d", num_of_structs);/*This reads the first number
at the top of the text file and which represents the number of patients in
the DB*/
/*I guess I'm doing a lot of wrong code down here?!*/
for (int j = 0; j < (*num_of_structs); j++) {
for (int picture = 0; picture < 2; picture++) {
fscanf(existing_file, "%d", patientRegister[j].pictures[picture]);
}
fscanf(existing_file, "%d %s", patientRegister[j].personal_number,
patientRegister[j].patient_name);}
fclose(existing_file);
}
答案 0 :(得分:0)
SELECT Name, STUFF((SELECT DISTINCT ',' + Number FROM BSFolks
WHERE Name = X.Name
AND (Number != '' AND Number IS NOT NULL)
FOR XML PATH ('')), 1, 1, '') AS Numbers
FROM BSFolks X
GROUP BY Name
的{{1}}格式说明符期望%d
的地址,即scanf
,而不是int
。这样就可以将读取的值写入变量。
所以你想要
int *
请注意,int
不需要fscanf(existing_file, "%d", &num_of_structs);
...
fscanf(existing_file, "%d", &patientRegister[j].pictures[picture]);
...
fscanf(existing_file, "%d %s", &patientRegister[j].personal_number, patientRegister[j].patient_name);
即可读入数组,因为数组会自动衰减为指向其第一个元素的指针。