文件I/O操作与进程管理全解
1. 使用流读取文件
在掌握了如何使用流写入文件之后,接下来我们将学习如何使用流读取文件。下面是具体的操作步骤:
1. 编写代码 :将以下代码保存为 stream-read.c 文件。
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fp; /* pointer to a file stream */
char linebuf[1024] = { 0 }; /* line buffer */
if ( argc != 2 )
{
fprintf(stderr, "Usage: %s [path]\n",
argv[0]);
return 1;
}
/* open file with read mode */
if ( (fp = fopen(argv[1], "r")) == NULL )
{
perror("Can't open file for reading");
return 1;
}
/* loop over each line and write it to stdout */
while(fgets(linebuf, sizeof(linebuf), fp)
!= NULL)
{
printf("%s", linebuf);
}
fclose(fp); /* clos
超级会员免费看
订阅专栏 解锁全文
1778

被折叠的 条评论
为什么被折叠?



