doujian1954 2018-06-19 15:30
浏览 13

如何在不丢失文件句柄的情况下截断文件中的n行

I got a file that other processes are currently writing and appending a new entry at the end of the file. I'm trying to figure out the most efficient way to do this in GO-Lang

I got a program currently written in PERL that does the following:

1)Make a copy of the current file

2)Checks the n of lines in the copied file

3)Truncates the n number of lines from the beginning of the original file

4)Original file retains any file handle that may have been writing to it during the time of the copy.

if ( -s $file){

      system("cp -f $file $file_copy");
      //Get the number of lines copied
      $tmp_linecount =`wc -l < $file_copy`;
      chomp($tmp_linecount);

      # truncate orignal file from beginning
      $command="sed '1," . $tmp_linecount ."d' $file | tee $file";

      system($command);
      $linecount=`wc -l < $file`;
      chomp($linecount);
      logh("$file_copy has $tmp_linecount records to process, $file has $linecount records left");
    }

Now i'm trying to solve this same problem in GO-Lang. I looked at truncating the file but it looks like it will truncate a file all the way down to the number of btyes you specified.

    err := os.Truncate("test.txt", 100)
if err != nil {
    log.Fatal(err)
}

At the end of the day What i'm trying to accomplish is reading a file that is currently adding new entries to the EOF. Process any new entries and delete the entries right after without stopping other processes from writing to the file at the same time.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号