我正在嘗試使用函式 open() 和 read() 從 txt 檔案中列印前 10 行。到目前為止,我已經設法列印了整個檔案,但是當我到達第 10 行的末尾時我遇到了停止代碼的問題。我該怎么辦?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(){
int fd = open("a.txt", O_RDONLY);
if(fd < 0){
printf("Error: %d\n", errno);
perror("");
}
char *c = (char*)calloc(100, sizeof(char));
ssize_t res;
int max = 0;
while(res = read(fd, c, 1) && max < 10){
if(res < 0){
printf("Error: %d\n", errno);
perror("");
}
c[res] = '\0';
if(c[res] == '\n'){
max ;
}
printf("%s", c);
}
close(fd);
return 0;
}
uj5u.com熱心網友回復:
以下始終將 position 設定res為'\0',然后立即檢查它是否為'\n'。
c[res] = '\0';
if(c[res] == '\n'){
max ;
}
這永遠不會成立。因此,max永遠不會增加,您將讀取整個檔案。
此外,res保存 的結果read(fd, c, 1) && max < 10。它需要括號來隔離對正確結果的分配:((res = read(fd, c, 1)) && max < 10盡管切換這些順序將有助于避免不必要的讀取)。
如果您一次讀取一個位元組的檔案,則無需分配如此大的緩沖區。單個位元組的存盤空間就足夠了。"%s"您可以使用"%c"列印單個字符(或使用write),而不是使用列印 NUL 終止的字串。
一個使用readand的例子write:
#include <unistd.h>
#include <fcntl.h>
int main(void) {
char byte;
int newlines = 0;
int fd = open("a.txt", O_RDONLY);
while (newlines < 10 && read(fd, &byte, 1) > 0) {
/* alternatively: printf("%c", byte); */
write(STDOUT_FILENO, &byte, 1);
if (byte == '\n')
newlines ;
}
close(fd);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350342.html
