c语言如何从文件中读取字符串

   2024-10-01 2970
核心提示:在C语言中,可以使用标准库函数fgets()或fscanf()来从文件中读取字符串。使用fgets()函数:#include stdio.hint main() {FILE *f

在C语言中,可以使用标准库函数fgets()或fscanf()来从文件中读取字符串。

使用fgets()函数:
#include <stdio.h>int main() {    FILE *file;    char str[100];    file = fopen("file.txt", "r");    if (file == NULL) {        printf("Error opening file\n");        return 1;    }    fgets(str, sizeof(str), file);    printf("String read from file: %s\n", str);    fclose(file);    return 0;}
使用fscanf()函数:
#include <stdio.h>int main() {    FILE *file;    char str[100];    file = fopen("file.txt", "r");    if (file == NULL) {        printf("Error opening file\n");        return 1;    }    fscanf(file, "%s", str);    printf("String read from file: %s\n", str);    fclose(file);    return 0;}

其中,"file.txt"是要读取的文件名,"r"表示以只读模式打开文件。fgets()函数会一次性读取整行字符串,而fscanf()函数会按照指定格式读取字符串。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号