首页 > 解决方案 > 我的程序创建了一个名为 date.in 的文件,但它没有插入所有数字

问题描述

编写一个 C 程序,从键盘读取一个最多 9 位的自然数 n,并创建包含数字 n 及其所有非零前缀的文本文件 data.out,在一行中,以空格分隔,按顺序价值下降。示例:对于 n = 10305,数据 file.out 将包含数字:10305 1030 103 10 1。

这是我做的:

#include <stdio.h>

int main()    
{    
 int n; 
 FILE *fisier;
 fisier=fopen("date.in","w");
 printf("n= \n");
 scanf("%d",&n);
 fprintf(fisier,"%d",n);

 while(n!=0)    
 {
    fisier=fopen("date.in","r");
     n=n/10;
     fprintf(fisier,"%d",n);    
 }

 fclose(fisier);
}

标签: c

解决方案


一些事情:

  1. 函数调用可能会返回错误。你需要每次都检查一下。

    fisier=fopen("date.in","w");

    这之后应该进行错误检查。要了解更多关于它返回的内容,您应该做的第一件事是阅读该函数的手册页。请参阅fopen() 的手册页。如果打开文件时出错,它将返回 NULL 并将 errno 设置为指示发生了什么错误的值。

    if (NULL == fisier)
    {
        // Error handling code
        ;
    }
    
  2. 您的下一个要求是用空格分隔数字。没有一个。以下应该做到这一点。

    fprintf(fisier, "%d ", n);
    
  3. 下一个主要问题是循环打开文件。就像您正试图打开一扇已经打开的门。

    fisier=fopen("date.in","r");
    
    if(NULL == fisier)
    {
        // Error handling code
        ;
    }
    
    while(n!=0)    
    {
        n=n/10;
        fprintf(fisier,"%d",n);    
    }
    
    fclose(fisier);
    
  4. 您没有检查的一个小问题是该号码的位数不超过 9 位。

    if(n > 999999999)
    

    在你得到一个数字后很合适。如果你也想处理负数,你可以按照你想要的方式修改这个条件。

简而言之,至少在开始时,该程序应该类似于以下内容:

#include <stdio.h>

// Need a buffer to read the file into it. 64 isn't a magic number. 
// To print a 9 digit number followed by a white space and then a 8 digit number.. 
// and so on, you need little less than 64 bytes. 
// I prefer keeping the memory aligned to multiples of 8.

char buffer[64];

int main(void)
{
    size_t readBytes = 0;
    int n = 0;

    printf("\nEnter a number: ");
    scanf("%d", &n);

    // Open the file
    FILE *pFile = fopen("date.in", "w+");
    if(NULL == pFile)
    {
        // Prefer perror() instead of printf() for priting errors
        perror("\nError: ");
        return 0;
    }

    while(n != 0)
    {
        // Append to the file
        fprintf(pFile, "%d ", n);
        n = n / 10;
    }

    // Done, close the file
    fclose(pFile);

    printf("\nPrinting the file: ");

    // Open the file
    pFile = fopen("date.in", "r");
    if(NULL == pFile)
    {
        // Prefer perror() instead of printf() for priting errors
        perror("\nError: ");
        return 0;
    }

    // Read the file
    while((readBytes = fread(buffer, 1, sizeof buffer, pFile)) > 0)
    {
        // Preferably better way to print the contents of the file on stdout!
        fwrite(buffer, 1, readBytes, stdout);
    }

    printf("\nExiting..\n\n");
    return 0;
}

请记住:阅读您的代码的人可能不了解所有要求,因此注释是必要的。其次,我对英语的理解达到了不错的水平,但我不知道“fisier”是什么意思。建议以易于理解变量用途的方式命名变量。例如,pFile是一个指向文件的指针。p在变量中立即给出了一个想法,即它是一个指针。

希望这可以帮助!


推荐阅读