我有一個文本文件。我必須從文本文件中讀取一個字符串。我正在使用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