【问题标题】:PHP Write string to new line for the first time and not at the end of filePHP第一次将字符串写入新行而不是文件末尾
【发布时间】:2013-08-20 04:32:25
【问题描述】:

使用 Codeigniter 函数write_file(),我可以像这样写入现有文件:

write_file("path_to_file", "String four"."\n", "a+");

假设我已经有一个这样的文件:

String one
String two
String three

使用 write_file("path_to_file", "String four"."\n", "a+") ,我在第一次写入文件时有以下输出:

String one
String two
String three String four

知道如何第一次将 String 4 写入换行符吗?如下图:

String one
String two
String three 
String four

谢谢。

【问题讨论】:

  • 可以先检查文件是否为空;如果是,只需写下该行。如果不是,请附加一个新行和您的内容。

标签: php codeigniter


【解决方案1】:

对这个 write_file() 函数了解不多,但鉴于你所说的,这应该可以工作:

write_file("path_to_file", "\n"."String four"."\n", "a+")

【讨论】:

  • 使用双引号时不需要连接第二个参数中的字符串:"\nString four\n"
  • @samitny,你是对的,但在这种情况下,连接可以方便地使代码更具可读性。如果我错了,请纠正我。
  • 也许更具可读性,即使很多 IDE 在大多数情况下都高亮这些 '\n'。但是没有串联的解决方案比另一个解决方案快约 35%。
【解决方案2】:

尝试在字符串四之前添加新行:

write_file("path_to_file", "\nString four\n", "a+")

【讨论】:

  • 您可能想看看为什么现有的最后一行(字符串三)缺少它应该有的换行符\n。如果写得正确,使用 \n,你就不必对字符串 4 做特殊的技巧了。
猜你喜欢
  • 2011-10-19
  • 2012-02-03
  • 2014-02-04
  • 2011-02-24
  • 2018-10-10
  • 1970-01-01
  • 2010-10-31
  • 1970-01-01
相关资源
最近更新 更多