如何打开一个文件来读取和其他写入C?

时间:2017-05-23 15:17:24

标签: c printf fopen

查看此代码

void readAndWrite() {
    char url[]="data.txt";
    char url2[]="output.txt";
    char data[256];
    FILE *arq;
    FILE *arqw;

    arq = fopen(url, "r");
    arqw = fopen(url2, "w");
    if(arq == NULL) {
        printf("Erro, nao foi possivel abrir o arquivo\n");
    } else {
        while(fgets(data, 256, arq) != NULL) {         
            fprintf(arqw,"This %s",data);
        }
    }
    fclose(arq);
    fclose(arqw);
}

打开文件没有问题。两者都不输入NULL if。但是,无法读取读取文件。

1 个答案:

答案 0 :(得分:0)

您确定创建了“data.txt”吗? 如果它不存在,arg将始终为NULL,您将获得错误打开文件。 阅读有关修饰符https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm

的信息

您可以通过errno读取错误 printf(“errno是%d,fd是%d \ n”,errno,arq);

char url[] = "data.txt";
char url2[] = "output.txt";
char data[256];
FILE *arq;
FILE *arqw;

arq = fopen(url, "r");
if (arq == NULL) {
    printf("Erro, nao foi possivel abrir o arquivo\n");
    printf("errno is %d and fd is %d\n", errno, arq);
}
else {
    arqw = fopen(url2, "w");
    while ((fgets(data, 256, arq)) != NULL) {
        fprintf(arqw, "This %s", data);
    }
    fclose(arq);
    fclose(arqw);
}