希望大佬可以帮我找出文件无法关闭的原因。

希望大佬可以帮我找出文件无法关闭的原因。

问题描述:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define count 1000  //人数上限
 FILE * fp;
void write(void); //写入结构体中
void save(void);  //存入文件中
void s_gets(char * st, int n);//升级版fgets
struct worker
{
    char ID[20];
    char name[20];
    char sex[10];
    char born[20];
    char edu[20];
    char position[20];
    char wage[10];
    char address[100];
    char tel[15];
}work[count];

int main(void)
{
    if((fp = fopen("E:\\work_list", "w+")) == NULL)
        {
            printf("We can not open this file");
            exit(1);
        }
    else
        printf("File is already opend\n");

    write();
    save();

    if( fclose(fp) == NULL )
    {
        printf("We can not close the file!");
        exit(1);
    }
    else
        printf("File close successful.");

    return 0;
}


void write(void) //写入结构体数组

{
    int n, i;

    printf("Please enter the count of max member:\n");
    scanf("%d", &n);

    printf("Please enter the stuff information:\n\n");

    for(i = 0; i < n; ++i)
    {
        printf("第 %d 人", i + 1);

        printf("Please enter the ID: ");
        s_gets(work[i].ID, 20);

        printf("Please enter the name: ");
        s_gets(work[i].name, 20);

        printf("Please enter the sex: ");
        s_gets(work[i].sex, 20);

        printf("Please enter the born: ");
        s_gets(work[i].born, 20);

        printf("Please enter the edu: ");
        s_gets(work[i].edu, 20);

        printf("Please enter the position: ");
        s_gets(work[i].position, 20);

        printf("Please enter the wage: ");
        s_gets(work[i].wage, 20);

        printf("Please enter the address: ");
        s_gets(work[i].address, 20);

        printf("Please enter the tel: ");
        s_gets(work[i].tel, 20);

    }
}

void save(void)  //存入文档
{
    int i;

    for(i = 0; i < count; ++i);
    {
        if(fwrite(&work[i], sizeof(struct worker), 1, fp) != NULL)
           {
             putc('\n', fp);
             putc('\n', fp);
           }

        else
            printf("Sorry");
    }


}

void s_gets(char * st, int n) //升级版fgets
{
    int i  = 0;
    char * pointer = NULL;

    pointer = fgets(st, n, stdin);
    if(pointer) 
    {
        while(st[i] != '\n' && st[i] != '\0')
        {
            i++;
        }

        if(st[i] == '\n')
        {
            st[i] = '\0';
        }
        else
        {
            while(getchar() != '\n')
                continue;

        }

    }
}

if( fclose(fp) == NULL ) 这个判断有问题,文件关闭成功会返回 0,NULL的值也是0,你应该用不等0去判断。

你可 用 perror("错误原因:");这句话打印下看看到底什么原因出错的。

出现了Invalid argument.但我还是不知道怎么改。

网上说把' \ '换成' / '但没用

好了,谢谢你

我能再问一下吗?就是这个程序写入的信息很奇怪,大概是" 口 口 "这样

一大堆空白加2口

很大可能是你在输出字符串的时候,没有给字符数组设置 '\0'

输入字符串

麻烦你了,谢谢