gpt4 book ai didi

c - 在遇到一定数量的换行符后,我的程序会返回我想要的正确位置吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:10 25 4
gpt4 key购买 nike

我正在尝试向后读取文件(比如文件末尾的 10 行)。每当它读取 '\n' 时,我都会增加我的换行计数器 (newline_counter)。一旦 newline_counter 达到 user_num(参数),比如 10 行,lseek() 将停止在当前位置(current_pos).我正在返回这个位置,以便我可以在另一个使用 lseek() 的函数中使用这个位置到这个位置,并从这个位置开始读取并写入直到文件末尾。我已经成功编译了程序,但是一旦我开始运行它,程序就一直在运行,没有任何输出。

int func_line_mode(int infile, int user_num) {
char c;
int newline_counter = 0;
int current_pos = 0;
int end = lseek(infile, 0, SEEK_END);

int counter = 0;

while (counter < end || newline_counter <= user_num) {
lseek(infile, current_pos, SEEK_END);
read(infile, &c, sizeof(char));
if (strcmp(&c,"\n") == 0) {
newline_counter++;
}
current_pos--;
counter++;
}

return current_pos;
}

最佳答案

您的代码存在一些问题:

  1. while条件错误,应该是:

    while (counter < end && newline_counter <= user_num)
  2. while 之后,最后一个换行符之前还有一个字节,所以准确地说你应该向前移动 2 个字节:

    if (current_pos < 0)
    current_pos += 2;
  3. lseek() 返回一个 off_t,而不是 int,所以你应该这样做:

    off_t end = lseek(infile, 0, SEEK_END);
  4. 因此,您用来进行比较的其他变量也应该是 off_t,最重要的是函数的返回类型。

  5. strcmp(&c,"\n") 是错误的,要比较单个字符,您只需执行 c == '\n'

第 1 条可能是您遇到问题的原因。其他点也应该固定,特别是第 4 点。


一旦上述所有问题都得到解决,该功能对我来说就可以正常工作了。这是一个工作示例:

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

off_t func_line_mode(int infile, int user_num) {
char c;
int newline_counter = 0;
off_t current_pos = 0;
off_t end = lseek(infile, 0, SEEK_END);
off_t counter = 0;

while (counter < end && newline_counter < user_num) {
lseek(infile, current_pos, SEEK_END);
read(infile, &c, 1);

if (c == '\n')
newline_counter++;

current_pos--;
counter++;
}

if (current_pos < 0)
current_pos += 2;

return current_pos;
}

int main() {
char buf[100];
int nread, nwrite;

int fd = open("test.txt", O_RDONLY);

// Last 3 lines.
off_t off = func_line_mode(fd, 3);

printf("off = %d\n", off);

// Go back.
lseek(fd, off, SEEK_END);

while (nread = read(fd, buf, 100)) {
nwrite = 0;

while (nwrite < nread)
nwrite += write(1, buf + nwrite, nread - nwrite);
}

return 0;
}

关于c - 在遇到一定数量的换行符后,我的程序会返回我想要的正确位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57707383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com