从txt文件读取时的文件指针 [英] file pointer while reading from txt file
问题描述
在我的应用程序中,我正在从文本文件中读取,但我需要关注我正在阅读的文件指针或已读取的文件内容。以及从哪里开始下一步。有两种情况我需要这样做。
CASE 1 ::当系统A和B在A写入的同时访问文件F时并且B正在读取文件F.所以系统A需要知道我已经阅读了多少以及从哪里进一步阅读?
案例2 ::当系统A从文件F1中读取并在分析后将文件F1行描述写入文件F2。如果检测到某些特定错误代码,则在读取文件F1时,我需要关闭文件F2并跳过ERROR LINE打开新文件F3,从ERRORLINE + 1开始重新开始F1分析。
您对这两种情况的建议将不胜感激。
感谢您耐心阅读
只需跟踪变量中的文件位置即可。文件I / O函数返回已读取或写入的项目数。
高级文件I / O方法通常提供返回当前位置的函数(例如ftell
)也可以使用。
在多个进程访问文件时必须特别小心同一时间。您应该避免从另一个进程实际打开的文件中读取;特别是当它不仅附加数据而且还插入/覆盖时。所以你应该检查你的案例1是否可以用另一种方式处理。
案例2的伪代码:
n = 2
in = open(F1,read)
out = open(F2,create_write)
while(!end_of_file(in))
{
line = readline(in)
description = parseline(line)
if(error)
{
close(out)
n = n + 1
out = open(Fn)
}
else
写(out,description)
}
close(in)
close(out)
In my application I am reading from the text file but i need to keep eye on the file pointer where I am reading or how much content of the file i already read. and where to start next. There are TWO situations where i need to do this.
CASE 1:: While 2 system A and B are accessing the file F at the same time where A is writing and B is reading the file F. So system A need to know how much i already read and from where to read further??
CASE 2:: While System A is reading from file F1 and after analyses writing FILE F1 line description into File F2. while reading the file F1 if some specific error code detected then I need to close the file F2 and skip the ERROR LINE open new file F3 to restart the F1 analysis from ERRORLINE+1 onward.
your suggestions to handle both cases would be appreciated.
Thanks for reading with patience
Just track the file position in a variable. File I/O functions return the number of items that has been read or written.
High level file I/O methods often provide functions that return the current position (e.g.ftell
) than can be used too.
Special care must be taken when files are accessed by multiple processes at the same time. You should avoid to read from a file that is actually opened for writing by another process; especially when that is not only appending data but also inserting / overwriting. So you should check if your case 1 can be handled in another way.
Pseudo code for case 2:
n = 2 in = open(F1, read) out = open(F2, create_write) while (!end_of_file(in)) { line = readline(in) description = parseline(line) if (error) { close(out) n = n + 1 out = open(Fn) } else write(out, description) } close(in) close(out)
这篇关于从txt文件读取时的文件指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!