c语言怎样读取文件中的字符串
在C语言中,可使用标准库函数`fscanf`或`fgets`来读取文件中的字符串。
1. 使用`fscanf`函数:
```c
#include
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("没法打开文件
");
return 1;
}
char str[100];
while (fscanf(file, "%s", str) != EOF) {
printf("%s
", str);
}
fclose(file);
return 0;
}
```
上述代码打开名为`example.txt`的文件并从中读取字符串,每次读取一个字符串并打印出来,直到文件末尾。
2. 使用`fgets`函数:
```c
#include
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("没法打开文件
");
return 1;
}
char str[100];
while (fgets(str, sizeof(str), file) != NULL) {
printf("%s", str);
}
fclose(file);
return 0;
}
```
上述代码使用`fgets`函数从文件中逐行读取字符串并打印出来,直到文件末尾。`sizeof(str)`指定了读取的最大字符数,避免了缓冲区溢出的问题。
TOP