从文件中读取字符串

6

我有一个文本文件,需要从中读取一个字符串。我正在使用C语言编写代码,请问有谁能帮助我?


3
你应该尝试付出一些努力寻找解决方案,而不是仅仅在这里发布问题并期望他人为你完成任务。同时,请让你的问题更加清晰明了。 - Vite Falcon
可能是在C中从文件读取字符串的重复问题。 - Sebastian D'Agostino
4个回答

20

使用C语言中的fgets函数从文件中读取字符串。

类似于:

#include <stdio.h>

#define BUZZ_SIZE 1024

int main(int argc, char **argv)
{
    char buff[BUZZ_SIZE];
    FILE *f = fopen("f.txt", "r");
    fgets(buff, BUZZ_SIZE, f);
    printf("String read: %s\n", buff);
    fclose(f);
    return 0;
}

出于简单起见,安全检查被省略。


5

这应该可以,它会读取整行(不太清楚你所说的“字符串”是什么意思):

#include <stdio.h>
#include <stdlib.h>

int read_line(FILE *in, char *buffer, size_t max)
{
  return fgets(buffer, max, in) == buffer;
}

int main(void)
{
  FILE *in;
  if((in = fopen("foo.txt", "rt")) != NULL)
  {
    char line[256];

    if(read_line(in, line, sizeof line))
      printf("read '%s' OK", line);
    else
      printf("read error\n");
    fclose(in);
  }
  return EXIT_SUCCESS;
}

如果一切顺利,返回值为1,出现错误则返回0。

由于使用的是普通的fgets()函数,因此它将保留行末的'\n'换行符(如果存在)。


3
你在问题中没有提到那一点。 - Stewart
2
@user556761 在这里,您需要接受人们对您众多问题的答案,提出更清晰的问题,并自己做一些工作。 - Jim Balter

5
void read_file(char string[60])
{
  FILE *fp;
  char filename[20];
  printf("File to open: \n", &filename );
  gets(filename);
  fp = fopen(filename, "r");  /* open file for input */

  if (fp)  /* If no error occurred while opening file */
  {           /* input the data from the file. */
    fgets(string, 60, fp); /* read the name from the file */
    string[strlen(string)] = '\0';
    printf("The name read from the file is %s.\n", string );
  }
  else          /* If error occurred, display message. */
  {
    printf("An error occurred while opening the file.\n");
  }
  fclose(fp);  /* close the input file */
}

在复制到“string”后,会自动添加一个终止空字符。因此,您不必执行“string[strlen(string)] = '\0';”。 - Imran

4

这是从文件获取字符串的简单方法。

#include<stdio.h>
#include<stdlib.h>
#define SIZE 2048
int main(){
char read_el[SIZE];
FILE *fp=fopen("Sample.txt", "r");

if(fp == NULL){
    printf("File Opening Error!!");

}
while (fgets(read_el, SIZE, fp) != NULL)
    printf(" %s ", read_el);
fclose(fp);
return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接