c程序无法正常读取文件

时间:2017-05-23 06:40:05

标签: c file

这是创建和编写文件的代码。

#include <stdio.h>

int main(void) {

FILE *cfPtr;

if((cfPtr = fopen("clients.txt","w")) == NULL) {


    puts("File could not be opened.");

}

else {

    puts("Enter the account, name, and balance.");
    puts("Enter EOF to end input.");
    printf("%s", "? ");

    unsigned int account;
    char name[30];
    double balance;

    scanf("%d %29s %lf", &account, name, &balance);
    //fprintf(cfPtr, "%d %s %f\n", account, name, balance);

    while(!feof(stdin) ) {

        fprintf(cfPtr, "%d %s %.2f\n", account, name, balance);
        printf("%s", "? ");
        scanf("%d%29s%lf", &account, name, &balance);

    }

    fclose(cfPtr);

}

return 0;

}

以下是读取文件和打印txt文件内容的代码。

#include <stdio.h>

int main(void) {

FILE *cfPtr;

if((cfPtr = fopen("clients.txt","r")) == NULL) {


    puts("File could not be opened.");

}

else {

    unsigned int account;
    char name[30];
    double balance;

    printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
    fscanf(cfPtr, "%d&29s%lf", &account, name, &balance);


    while(!feof(cfPtr)) {

        printf("%-10d%-13s%7.2f\n", account, name, balance);
        fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);

    }

    fclose(cfPtr);
}

return 0;

}

文件内容:

1 John 45.54        
2 Mike 56.65                
3 Patrick 23.32

写作程序的输入:
Inputs of the writing program

阅读程序的输出:
Output of the reading program

我从C How to Program book第8版中复制了代码。

这里有什么问题?

2 个答案:

答案 0 :(得分:0)

在创建和编写文件代码时,使用ctrl + z退出进程。因此,在这种情况下,进程将退出而不关闭文件(clients.txt)。以下是更改。

#include <stdio.h>

int main(void) {
FILE *cfPtr;

if((cfPtr = fopen("clients.txt","a")) == NULL) {
puts("File could not be opened.");

}

else {
puts("Enter the account, name, and balance.");
puts("Enter EOF to end input.");
printf("%s", "? ");

unsigned int account;
char name[30];
double balance;

scanf("%d %29s %lf", &account, name, &balance);

while(!feof(stdin) ) {
    if((cfPtr = fopen("clients.txt","a")) == NULL) 
    {
        puts("File could not be opened.");
        break;
    }
    fprintf(cfPtr, "%d %s %.2f\n", account, name, balance);
    printf("%s", "? ");
    scanf("%d %29s %lf", &account, name, &balance);
    fclose(cfPtr);
}
    fclose(cfPtr);
}

return 0;

}

在读取文件代码时,您必须以与存储时相同的格式读取数据。您通过在变量之间提供空间来存储数据。以下是更改。

#include <stdio.h>

int main(void) {

FILE *cfPtr;

if((cfPtr = fopen("clients.txt","r")) == NULL) {


puts("File could not be opened.");

}

else {

unsigned int account;
char name[30];
double balance;

printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
    fscanf(cfPtr, "%d %29s %lf", &account, name, &balance);


while(!feof(cfPtr)) {


    printf("%-10d%-13s%7.2f\n", account, name, balance);
    fscanf(cfPtr, "%d %29s %lf", &account, name, &balance);

}

fclose(cfPtr);
}

return 0;

}

答案 1 :(得分:0)

(代表OP发布)

我没有使用调试器,所以我找不到可以像这样解决的小错误:

"%d&29s%lf" -> "%d%29s%lf"

在做出改变后,我得到了正确的结果。