c语言中从文件件读一行的函数,C语言,有没有从文件中读取一行的函数

在Linux中,fgets函数用于从流中读取一行数据,直到遇到换行符或达到指定长度n-1。尽管fgets在TC下与Linux下的参数略有不同,但仍然可以使用。使用fgets时需注意,如果输入行长度超过缓冲区大小,可能导致不确定行为。推荐使用fgets代替gets以避免潜在问题。示例代码展示了如何使用fgets读取并复制文件内容。
摘要由CSDN通过智能技术生成

Linux 下的C语言有没有读取一行的函数

原来TC下fgets()好像是读取一行的,但在linux下该函数的参数改变了,

为读取制定长度的字符串。

望高手指教

|

还是用fgets呀

gets, fgets -- get a string from a stream

Synopsis

#include

char  * gets (char  * s);

char  * fgets (char  * s, int n, FILE  * stream);

Description

gets reads characters from the standard input stream (see intro(3)),

stdin, into the array pointed to by s, until a newline character is

read or an end-of-file condition is encountered. The newline character

is discarded and the string is terminated with a null character.

fgets reads characters from the stream into the array pointed to by s,

until n -1 characters are read, or a newline character is read and

transferred to s, or an end-of-file condition is encountered. The

string is then terminated with a null character.

When using gets, if the length of an input line exceeds the size of s,

indeterminate behavior may result. For this reason, it is strongly

recommended that gets be avoided in favor of fgets.

Errors

If end-of-file is encountered and no characters have been read, no

characters are transferred to s and a null pointer is returned. If a

read operation was attempted, and an error occurs, such as trying to

use these functions on a file that has not been opened for reading, a

null pointer is returned. If end-of-file is encountered, the EOF

indicator for the stream is set. Otherwise s is returned.

The functions gets and fgets fail when the file is a regular file and

an attempt was made to read at or beyond the offset maximum associated

with the corresponding stream. There is no data transfer.

函数一直读到换行或者n个数据才停止,所以当n指定很大的时候,肯定读取1行了

|

用fscanf标准读入

for example

fscanf(file,"%d %s",id,name)

完全是标准读入 一一对应

|

标准io 是fgets gets 无缓存io read 你要设置终端模式为行缓存 为 文件一行的长度。

推荐标准io.

|

int main(int argc, char *argv[]){

FILE *in, *out;

char buffer[256];

if((in = fopen(argv[1], "r")) != NULL && (out = fopen(argv[2]), "w")) != NULL){

while(fgets(buffer, sizeof(buffer), in)){

fputs(buffer, out);

}

}

fclose(in);

fclose(out);

}

|

楼上说的都对!

随便一本c语言书上都有的

|

嗯,谁来总结一下读文件的各种方式?

|

fgets

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值