文件路径读取正确但不创建文件或写入文件

时间:2021-01-31 21:23:57

标签: c file

我有一个 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);
}

它应该将有关数据的信息打印到为此目的创建的文本文件中。 write 变量似乎按照它应该的方式保存路径,代码完成没有问题,但是当我去检查没有创建 .txt 文件时,我觉得它真的很愚蠢,我忽略了但我看不到找到它。困扰我的一件事是我第二次打印 write 变量以检查它是否一切正常,它打印了正确的路径,前面有一些乱码。

1 个答案:

答案 0 :(得分:1)

问题好像是这一行

FILE * file1 = fopen("write", "w+");

我想,它应该读

FILE * file1 = fopen(write, "w+");

没有将变量名括起来。


另一个重要的点是 path 数组的大小。它只有 20 字节大,而 write 似乎也是 20 字节。如果给定的名称足够大,文本 C:\PC\<write>.txt 可能会变得大于 20 个字节。这将导致写入超出数组,并可能解释您看到的“乱码”。

相关问题