clang-format 不会修改磁盘上的文件

Try*_*yer 2 c++ 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在上面运行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...
                                                                    ^
Run Code Online (Sandbox Code Playgroud)

在运行时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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

alf*_*lfC 6

man clang-format

       -i                         - Inplace edit <file>s, if specified.
Run Code Online (Sandbox Code Playgroud)

  • @Tryer 是的,这是标准行为。几乎所有 UNIX 工具都是这样工作的:除非用户明确请求,否则不要修改用户数据。 (3认同)
  • @spectras 是的,根据经验,不要使用相同的源和接收器,因为它有时会损坏文件(例如“工具 A.txt &gt; A.txt”)。不确定这是否适用于“clang-format”。 (2认同)