c - 我的程序创建了一个名为 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);
}
解决方案
一些事情:
函数调用可能会返回错误。你需要每次都检查一下。
fisier=fopen("date.in","w");
这之后应该进行错误检查。要了解更多关于它返回的内容,您应该做的第一件事是阅读该函数的手册页。请参阅fopen() 的手册页。如果打开文件时出错,它将返回 NULL 并将 errno 设置为指示发生了什么错误的值。
if (NULL == fisier) { // Error handling code ; }
您的下一个要求是用空格分隔数字。没有一个。以下应该做到这一点。
fprintf(fisier, "%d ", n);
下一个主要问题是循环打开文件。就像您正试图打开一扇已经打开的门。
fisier=fopen("date.in","r"); if(NULL == fisier) { // Error handling code ; } while(n!=0) { n=n/10; fprintf(fisier,"%d",n); } fclose(fisier);
您没有检查的一个小问题是该号码的位数不超过 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
在变量中立即给出了一个想法,即它是一个指针。
希望这可以帮助!
推荐阅读
- r - serve_site 加载核心 R 库, build_site 不在 blogdown 中
- batch-file - 在批处理中对字符串使用 %~n 两次
- java - Java:使用 AWT 按钮断开与聊天服务器的连接
- python - 如何使输入()的输出提示为彩色(python)?
- sql - 如何在 Oracle 中将输入限制为仅整数?
- url - 使用 biblatex 的 make4ht 在使用标题字段时使用 \url 的记录失败,但在消除标题字段时失败
- python - Pandas TypeError:DataFrame 类型的对象不是 JSON 可序列化的
- google-cloud-platform - Google 的“OAuth 客户端已删除”是否意味着密钥无效?
- java - 用Java编写2个条件的4种可能性的最佳方法是什么
- amazon-ec2 - 在 AWS 中,如何为在私有子网中加入 AWS AD 域的实例配置 SSM?