繁体   English   中英

从文件中读取并将其存储在变量c中

[英]read from a file and store it in a variable c

我正在尝试从文件中逐字符准备好并将其存储在变量中。 我只需要文件的第一行,所以我使用'\\ n'或EOF停止读取字符,并且我还需要存储空格。 听到是我的程序,但是我在编译时得到警告,例如指针和整数之间的比较。当我运行时,我遇到了段错误

#include<stdio.h>
#include<string.h>

void main()
{
  FILE *fp;
  char ch;
  char txt[30];
  int len;
  fp=fopen("~/hello.txt","r");
  ch=fgetc(fp);
  while(ch != EOF || ch!="\n")
  {
    txt[len]=ch;
    len++;
    ch=fgetc(fp);
  }
   puts(txt);
}

您正在与错误的事物进行比较。 尝试:

ch != '\n'
      ^  ^

另外,正如在其他答案中所发现的那样,您正在使用len而不进行初始化。

最后,您确实意识到fgets也可以做到这一点。 您可以将其重写为:

if (fgets(txt, sizeof txt, fp))
    ...

1) len未启动

int len=0;

2)从fgetc()页面:

int fgetc ( FILE * stream );

因此fgetc()返回int而不是char因此您必须将ch定义为int

int ch;

3)除引号外while条件应使用&&而不是||检查。

while(ch != EOF && ch!='\n')

4)从文件读取完成后,必须在txt缓冲区的末尾添加null终止符。

while循环后添加此行

txt[len]='\0';

顺便说一句,您可以使用fscanf()阅读第一行,它更容易。 只需使用以下代码

fscanf(fp, "%29[^\n]", txt);

"%[^\\n]"意味着fscanf将从fp读取除'\\n'字符以外的所有字符,如果得到该字符,它将停止读取。 因此, fscanf将读取fp所有字符,直到找到'\\n'字符,并将其保存到缓冲区txt中,最后使用null终止符。

"%29[^\\n]"意味着fscanf将从fp读取所有字符,直到找到'\\n'字符或直到达到29个已读字符为止,然后将它们保存到缓冲区txt中,最后使用空终止符。

len没有初始化,因此您可能正在尝试写txt末尾以外的内容。 修复很简单-声明时将其初始化为0

int len = 0;

除了cnicutar指出的错误外,还应该在使用fp之前检查fopen的返回值。

#include<stdio.h>
#include<string.h>

void main()
{
  FILE *fp;
  char ch;
  char txt[30];
  int len = 0;
  fp=fopen("~/hello.txt","r");
  if(!fp) {
    printf("Cannot open file!\n");
    return;
  }
  ch=fgetc(fp);
  while(ch != EOF && ch!= '\n' && len < 30)
  {
    txt[len] = ch;
    len++;
    ch=fgetc(fp);
  }
  txt[len] = 0;
  puts(txt);
}

该程序可以帮助您解决问题。

     #include<stdio.h>

     int main()
     {
       FILE *fp;
       int ch;
       char txt[300];
       int len=0;
       fp=fopen("tenlines.txt","r");

       do{
           ch=fgetc(fp);
           txt[len]=ch;
           len++;
         } while(ch!=EOF && ch!='\n');
     fclose(fp);
     puts(txt);

     return 0;
    }

暂无
暂无

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

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