数据不会写入C中的文件

时间:2017-03-10 16:47:55

标签: c file

我正在尝试将数据输入DATA文件,读取它并分别在EVENODD文件中写入偶数和奇数。

我编写了以下代码来从用户那里获取输入并将其存储在DATA文件中。然后通过阅读来检查数字是偶数还是奇数。如果数字是偶数,则数字会添加到EVEN文件中,否则会在ODD文件中添加。

#include<stdio.h>

void main(){

FILE *DATA, *EVEN, *ODD;
int number, i;

printf("Enter Contents of the DATA file\n\n");
DATA = fopen("DATA", "w");

for(i = 1; i<=30; i++){
    scanf("%d", &number);
    if(number == -1) break;
    putw(number, DATA);
}
fclose(DATA);

DATA = fopen("DATA", "r");
EVEN = fopen("EVEN", "w");
ODD = fopen("ODD", "w");

while((number = getw(DATA)) != EOF){
    if((number % 2 == 0)) putw(number, EVEN);
    else putw(number, ODD);
}

fclose(DATA);
fclose(EVEN);
fclose(ODD);

fopen("EVEN", "r");
fopen("ODD", "r");

printf("\n\nContents of EVEN file\n\n");
while((number = getw(EVEN)) != EOF) printf("%4d", number);

printf("\n\nContents of ODD file\n\n");
while((number = getw(ODD)) != EOF) printf("%4d", number);
}

上面的代码没有给出任何奇数。我的代码出了什么问题?

  

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

问题是1:在你的逻辑中(偶数测试应该是数字%2 == 0),你需要在重新打开文件时设置文件指针这里是固定代码:(我建议也检查何时文件打开并在完成后关闭它们。)

void main() {

    FILE *DATA, *EVEN, *ODD;
    int number, i;

    printf("Enter Contents of the DATA file\n\n");
    DATA = fopen("DATA", "w");
    if (DATE == NULL)
    {
        // some error
    }

    for (i = 1; i <= 30; i++) {
        scanf("%d", &number);
        if (number == -1) break;
        putw(number, DATA);
    }
    fclose(DATA);

    DATA = fopen("DATA", "r");
    EVEN = fopen("EVEN", "w");
    ODD = fopen("ODD", "w");
    if (DATE == NULL || EVEN == NULL || ODD == NULL)
    {
        // some error
    }

    printf("\n\nData File Contains:\n");
    while ((number = getw(DATA)) != EOF) {
        if ((number % 2 == 0)) putw(number, EVEN);
        else putw(number, ODD);
        printf("%4d", number);
    }

    fclose(DATA);
    fclose(EVEN);
    fclose(ODD);

    EVEN = fopen("EVEN", "r");
    ODD = fopen("ODD", "r");

    printf("\n\nContents of EVEN file\n\n");
    while ((number = getw(EVEN)) != EOF) printf("%4d", number);

    printf("\n\nContents of ODD file\n\n");
    while ((number = getw(ODD)) != EOF) printf("%4d", number);

    printf("\nPressAnyKey\n");

    fclose(EVEN);
    fclose(ODD);
}