简体   繁体   English

C,读取文本文件

[英]C, Reading A Text File

I'm sorry if this is a dumb question, but I tried many different sources and I'm still not getting what I want. 如果这是一个愚蠢的问题,我感到很抱歉,但是我尝试了许多不同的资源,但仍然没有得到想要的东西。 I'm working on a program that reads from a text file, and in the code below, I'm trying to read the first line that will give me the number of resistor color codes were created below it. 我正在研究一个从文本文件读取的程序,在下面的代码中,我试图读取第一行,该行将给我提供在其下创建的电阻器颜色代码的数量。 I'm trying to read the number (n) and simply print it to see that it reads, but I get nothing. 我正在尝试读取数字(n)并简单地打印以查看其读数,但是我什么也没得到。 It seems so simple, but I can't seem to get it. 看起来很简单,但我似乎无法理解。

`FILE *fpinpt;
FILE *fpoutpt;
FILE *fpnom;
int n, *ptr;
double a, b, c, d, e, f, g, h, i, j, k, l;
fpinpt= fopen("F:\EGR 107\EE\HW 4\resistorInput.txt","r");
fpoutpt= fopen("F:\EGR 107\EE\HW 4\resistorOutput.txt","w");
fpnom= fopen("F:\EGR 107\EE\HW 4\resistorNominal.txt","w");
fscanf(fpinpt,"%d\n",n);
printf("%d",n);
ptr=(int*)calloc(n, sizeof(int));
if (fpinpt==NULL)
{
    printf("Error reading resistor file\n");
    fclose(fpinpt);
}
if (ptr==NULL) printf("Error, memory not allocated\n");

` `

in your code 在你的代码中

fscanf(fpinpt,"%d\n",n);

should be 应该

fscanf(fpinpt,"%d",&n);

Also, always check for the return value of fscanf() , fopen() to ensure proper input/ operation. 另外,请始终检查fscanf()fopen()的返回值,以确保正确的输入/操作。

That said, you don't need to cast the return value of malloc() and family. 就是说,您不需要 malloc()和family的返回值。

The main cause of problems is that you never check for errors. 问题的主要原因是,您永远不会检查错误。 For every fopen() there must be a 对于每个fopen() ,必须有一个

if (fopenedFile == NULL)
    ohNoMust_ICannotUse_fopenedFile();

now to why are your fopen() 's failing it's because you haven't escaped the '\\' character, so each file name should fix it like this 现在,为什么您的fopen()失败了是因为您没有转义'\\'字符,所以每个文件名都应该像这样修复它

"F:\\EGR 107\\EE\\HW 4\\resistorInput.txt"

Then, files will be opened, but fscanf() will not work because of what the other answer already (" while I was editing mine ") addressed. 然后,将打开文件,但是fscanf()将无法工作,因为已经解决了其他答案(“ 在编辑我的我的代码时 ”)。

NOTE : 注意

Please read both answers, it doesn't make sense to repeat what @ SouravGhosh already said. 请阅读两个答案,重复@ SouravGhosh已经说过的话是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM