【问题标题】:clang-format does not modify file on diskclang-format 不修改磁盘上的文件
【发布时间】:2021-11-02 16:34:12
【问题描述】:

我有以下格式错误的文件,test.cpp

#include "maininclude.h"

int main() {
             class SIMPLE smpl;
  for (int i = 1; i < 100; 
  i++) {
      printf("Printing %d", i); // Trying out different stuff...
getchar();
  }
}

我想在其上运行clang-format。在运行之前,为了直观地查看要修改的地方,我运行了clang-format -n test.cpp。这可以正确识别由于终端上的错误格式和输出而将更改的点:

test.cpp:3:13: warning: code should be clang-formatted [-Wclang-format-violations]
int main() {
            ^
test.cpp:5:27: warning: code should be clang-formatted [-Wclang-format-violations]
  for (int i = 1; i < 100; 
                          ^
test.cpp:6:9: warning: code should be clang-formatted [-Wclang-format-violations]
  i++) {
        ^
test.cpp:7:64: warning: code should be clang-formatted [-Wclang-format-violations]
          printf("Printing %d", i); // Trying out different stuff...
                                                                    ^

在运行clang-format test.cpp 时,我获得了正确格式化的文件的外观(此显示在终端上):

#include "maininclude.h"

int main() {
  class SIMPLE smpl;
  for (int i = 1; i < 100; i++) {
    printf("Printing %d", i); // Trying out different stuff...
    getchar();
  }
}

然而,运行上述命令并不会改变磁盘上实际的test.cpp 文件。是否有单独的选项/命令让clang-format 继续应用其更改并将文件保存在磁盘上?

【问题讨论】:

    标签: c++ clang-format


    【解决方案1】:

    来自man clang-format:

           -i                         - Inplace edit <file>s, if specified.
    

    【讨论】:

    • 确实,这成功了。因此,根据设计,clang-format test.cpp 仅在终端上输出文件的外观。
    • @Tryer 是的,这是标准行为。几乎所有的 Unix 工具都是这样工作的:除非他们明确要求,否则不要修改用户数据。
    • @spectras 是的,根据经验,不要使用相同的源和接收器,因为它有时会损坏文件(例如tool A.txt &gt; A.txt)。不确定这是否适用于clang-format。
    • 确实如此。对于任何工具都是如此,因为使用这种语法 A.txt 会在 before tool 启动之前被清除。
    【解决方案2】:

    使用-i 选项,表示Inplace edit &lt;file&gt;s。它将就地编辑文件。

    【讨论】:

    • 你认为它会吗?
    • @sweenish,我试图获得答案所需的 38 个字符。我的第一次尝试“使用-i 选项”太短了,所以我添加了“无用”字样。当我第二次提交答案时,它不再是第一个答案了。不过,我已经删除了“我认为会”。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2020-08-28
    • 2016-03-06
    相关资源
    最近更新 更多