[英]To count the total number of lines in a file using Unix system call in C
[英]c program to count lines in file using system calls
我正在編寫一個C程序,使用open(),read(),write()close()之類的系統調用來計算文件中的行數。 我用庫執行的同一程序調用了fopen(),fread(),fwrite(),並且運行良好,但是僅通過系統調用,我就陷入了困境。
int fd1; // file descriptor
fd1=open("f1.txt",O_RDONLY); // opening file
read(fd1, buffer , 1); // reading 1 byte from file
// now comparing
if (buffer == '\n')
line++;
我的問題在這里:
如果(myb =='\\ n')
我不知道如何比較緩沖區中的數據。 我正在嘗試使用緩沖區,但沒有成功。 請幫助!
您將指針( buffer
)與char( '\\n'
)進行了比較
您應該取消引用指針,例如:
if (*buffer == '\n')
要么
if (buffer[0] == '\n')
好在這里我解決如何計算文件中的單詞
while(sc !=EOF)
{
sc=fgetc(at); // at is file stream
if(isspace(sc)) sp=1;
else if(sp) {
++words;
sp=0;
}
}
系統調用除了提供您所提供的內容外不會做任何緩沖,因此您確實不想一次只讀取一個字節。 在一定程度上,更大的緩沖區是更好的,但是過去幾個千字節(或左右)增加緩沖區大小僅獲得多一點的性能,以換取使用相當多的內存。
char buffer[16384];
int bytes_read;
unsigned lines = 0;
int fd1 = open("name.txt", O_RDONLY);
while (bytes_read = read(fd1, buffer, sizeof(buffer)) {
int i;
for (i=0; i<bytes_read; i++)
if (buffer[i] == '\n')
++lines;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.