![](/img/trans.png)
[英]Null terminating char array in C and difference between using read and fgets
[英]Difference between read() and fgets() in C
我想從標准輸入 stream 中讀取。 使用 read() 或 fgets() 從標准輸入 stream 讀取是否有任何區別。
我正在使用 fgets 附加以下兩段代碼並閱讀。 使用 fgets,我可以使用 java 程序輕松地寫入和讀取 c 程序。 隨着讀寫我的 java 程序掛起等待 output 來自 C 程序沒有來。
我只是在閱讀將其保存在 buf 中並在其上附加 A 的行。
Java 程序能夠與以下與 fgets 和 puts 一起工作的程序對話。
#include <stdio.h>
#include <string.h>
#define SIZE 200000
main()
{
int rc;
int df;
int i;
char buf[SIZE];
for(i=0;i<=120000;i++) {
memset(buf,'\0',SIZE);
if(!fgets(buf,SIZE-1,stdin))
continue;
strcat(buf,"A_A_A_A_A_A_A");
puts(buf);
}
}
但不是 read() 和 write()
main()
{
int rc;
int df;
int i;
char buf[32768];
rc = fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
//rc = fcntl(fileno(stdout), F_SETFL, O_NONBLOCK);
FILE *fp;
for (;;)
{
int rc=-1;
memset(buf,'\0',32768);
//rc = fread(buf,5, 1, stdin);
rc = read(fileno(stdin),buf,32768);
if (rc > 0)
{
strcat(buf,"B_B_B_B_B_B_B_B_B");
write(fileno(stdout),buf,strlen(buf));
}
}
}
有人能說出原因嗎。 我仍然很難弄清楚
fgets
是 function, read
是系統調用fgets
是標准 C, read
不是fgets
是 stdio 緩沖的, read
不是fgets
與FILE *
一起使用, read
與文件描述符一起使用fgets
讀取到換行符, read
讀取你告訴它多少需要更多?
有一個重要的替代方案( fread
)位於中間,所以這個問題真的應該分為兩部分 - 並且兩者都已經在 SO 中得到很好的回答:
fread
和read
和有什么不一樣?
fgets
和fread
和有什么不一樣?
快速經驗法則:如果您打算逐行讀取文本數據,請使用fgets
,在其他地方使用fread
。
#include <stdio.h>
char fgets (char * restrict str, int size, FILE * restrict stream)
fgets() function 從給定的 stream 中讀取最多比 size 指定的字符數少一個並將它們存儲在字符串 str 中。 當發現換行符、文件結尾或錯誤時,讀取停止。
參考: fgets()
#include <unistd.h>
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
read() function 將嘗試從與打開的文件描述符 fildes 關聯的文件中讀取 nbyte 字節到 buf 指向的緩沖區中。 未指定同一 pipe、FIFO 或終端設備上的多個並發讀取的行為。
參考: 讀()
一個( read
)嘗試讀取指定數量的字節,而另一個( fgets
)嘗試讀取一行並將在換行處停止。
這兩個函數沒有任何共同之處。 read 是一個 POSIX 系統調用,它從文件句柄中讀取。 fgets 是從 FILE * 讀取的 C 庫 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.