我有一个文本文件。我必须从文本文件中读取一个字符串。我正在使用c代码。任何身体可以帮助吗?从文件中读取字符串
回答
这应该工作,它会读取一整行(这不是很清楚你所说的“字符串”的意思):
#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'换行符(如果存在)。
这里我想从文件中读取特定的字符串。 – user556761 2011-03-01 11:15:01
你没有在问题中说过。 – Stewart 2011-03-01 11:16:59
@ user556761在这里,您想接受人们对众多问题的回答,提出更清晰的问题,并自行做一些工作。 – 2011-03-01 12:10:55
使用fgets
从C中的文件读取字符串。
喜欢的东西:避免为了简便
#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;
}
安全检查。
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 */
}
- 1. 从文件中读取字符串:Javascript?
- 2. 从文件中读取字符串
- 3. 从文件中读取字符串。 QTextStream不读文件
- 4. 字符串内插字符串从文件中读取字符串
- 5. 如何从文件读取XML字符串到字符串?
- 6. 从批处理文件中的文件中读取字符串
- 7. 从文件中读取字符串后替换字符java
- 8. 从文件中读取大(450000+个字符)字符串
- 9. 从字符串中读取字符或从字符串中获取字符
- 10. 从Hexidimal文字读取到字符串
- 11. 从文本文件中读取字符
- 12. 获取从文件中读取的字符串编码
- 13. 从同一文件中读取字符串和字节java
- 14. 从文件中读取逐字字符串
- 15. 从文本文件中读取3个字符串
- 16. 从文本文件中读取巨大的字符串
- 17. 如何从文本文件中读取特定的字符串
- 18. 尝试从文本文件中读取字符串
- 19. 如何使用CAPL从文本文件中读取字符串?
- 20. 我如何从文本文件中读取字符串?
- 21. 如何使用PowerShell从文本文件中读取字符串
- 22. Python - 从文本文件中读取字符串
- 23. 从文本文件中读取字符串和整
- 24. 从java文本文件中读取字符串
- 25. 如何从文本文件中读取字符串
- 26. 从正在读取的文本文件中读取输入字符串4gl
- 27. 从文件中读取到的字符
- 28. 从文件中读取字符
- 29. 从文件中读取字符
- 30. 从SML文件中读取字符
您应该尝试努力寻找解决方案,而不是只是在此发布期望别人为您完成工作。此外,让你的问题更清楚。 – 2011-03-01 12:45:06