使用低级 I/O 函数从文件中获取单行的长度
我正在编写一个例程来检查用户名是否已在内部数据库上注册。 特别是以下函数“应该”仅返回数据库的一行长度:
int line_bytes(int database, off_t line){
int c, len;
lseek(database, line, SEEK_CUR);
for(len = 0; read(database, &c, 1) == 1; len++)
if(c == '\n');
return len;
}
但是,它返回整个文件长度(文件上的所有字符)。那么问题来了:问题是read()吗?低输入函数在一个周期内读取所有文件并返回整个文件长度?
为了帮助您,数据库格式为:
username \t password\n
...\n
...\n
last-username \t last-passwotd\n
I am writing a routine to check if a username has already been registered on an internal database.
In particular the following function "should" return the length of only one single line of the database:
int line_bytes(int database, off_t line){
int c, len;
lseek(database, line, SEEK_CUR);
for(len = 0; read(database, &c, 1) == 1; len++)
if(c == '\n');
return len;
}
Though, it returns the whole file length (all the chars on the file). So the question: is the problem read()? The low-input function read all the file in one single cycle and return the whole file length?
To help, the database format is:
username \t password\n
...\n
...\n
last-username \t last-passwotd\n
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
if 语句中有一个
;
。将其删除。 ;)还在循环后添加一个 return,如
return -1;
您的代码执行错误:
更好
char c
因为当读取 1 个字节时, int 的其他字节未初始化,在大端字节序上,字符被放错位置。You have a
;
on the if-statement. Remove it. ;)Also add a return after the loop, like
return -1;
Your code does erroneously:
Better
char c
as when 1 byte is read the other bytes of the int are uninitialized, and on a big-endian the char is misplaced.