我有一个switch语句,其中一个情况如下:
printf( "What is the name of the file you want to store data in? n");
scanf( " %19s" , write);
writef(tamanho, write, &a);
它调用的函数是:
void writef(int tamanho, char write[20], Array * a){
char path[20] = {"C:\PC\"};
write = strcat(path, write);
write = strcat(write, ".txt");
printf(" %19s n", write);
FILE * file1 = fopen("write", "w+");
printf(write);
if(file1 == NULL)
{
printf("Error");
exit(1);
}
for (int i = 0; i < tamanho; i++){
fprintf(file1, "HELLO FRIEND I HAVE ARRIVED");
fprintf(file1, "Dimensao: %d n", &tamanho);
fprintf(file1, "Nome : %59s n", a->array[i].nome);
fprintf(file1, "Morada : %79s n" ,a->array[i].morada);
fprintf(file1,"Codigo Postal : %30s n" , a->array[i].codigop);
fprintf(file1, "Telefone : %20s n", a->array[i].telefone);
fprintf(file1, "Data de nascimento : %10s n",a->array[i].aniver);
fprintf(file1, "Genero : %c n", &a->array[i].sexo);
fprintf(file1, "Profissao : %59s n",a->array[i].prof);
fprintf(file1, "Altura : %d n",&a->array[i].altura);
fprintf(file1, "Contribuinte : %d n",&a->array[i].contribuinte);
}
printf("Dados guardados com sucesso n");
fclose(file1);
}
它应该将有关数据的信息打印到为此目的创建的文本文件中。写变量似乎保持路径,因为它应该,代码完成没有问题,但当我去检查没有。txt文件被创建,我觉得它的东西真的很愚蠢,我忽略了,但我似乎找不到它。困扰我的一件事是,当我第二次打印write变量来检查它是否正确时,它打印了正确的路径,前面有一点乱码。
问题似乎出在这一行
FILE * file1 = fopen("write", "w+");
我想应该是
FILE * file1 = fopen(write, "w+");
,没有变量名周围的引号。
另一个重要的点是path
数组的大小。它只有20字节大,write
似乎也是20字节。如果给定的名称足够大,则文本C:PC<write>.txt
可能大于20字节。这将导致写入超出数组,并可能解释"乱码"。你看。