Posted: . At: 10:37 AM. This was 3 years ago. Post ID: 15252
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Properly remove all trailing whitespaces from a C source file.


Trailing whitespace in a C source file is very annoying, especially if it is a very large file. There is an easy way to fix this with the Linux command line.

This sed(1) one-liner will remove all spaces from the file, erasing all of the unwanted spaces after characters that is the bane of autistic programmers.

┌──[jason@192.168.1.2][~/Documents]
└──╼  ╼ $ sed 's/^[ \t]*//;s/[ \t]*$//' < mytesting.c > testingout.c

Then the C program will look like this.

┌──[[email protected]][~/Documents]
└──╼  ╼ $ cat testingout.c 
#include <unistd.h>
#include <stdio.h>
 
int main(int argc, char **argv, char **env)
{
int STDIN_PIPE[2];
int STDOUT_PIPE[2];
 
pipe(STDIN_PIPE);
pipe(STDOUT_PIPE);
pid_t pid = fork();
if(pid == 0)
{
char *path = "/path/to/binary";
char *args[2];
args[0] = path;
args[1] = NULL;
close(STDIN_PIPE[1]);
close(STDOUT_PIPE[0]);
dup2(STDIN_PIPE[0], STDIN_FILENO);
dup2(STDOUT_PIPE[1], STDOUT_FILENO);
execve(path, args, env);
}
else
{
char buf[128];
close(STDIN_PIPE[0]);
close(STDOUT_PIPE[1]);
while(read(STDOUT_PIPE[0], buf, 1))
write(1, buf, 1);
}
}

Once that is done, just use the indent utility to reformat the code properly.

┌──[jason@192.168.1.2][~/Documents]
└──╼  ╼ $ indent testingout.c

Now the code is properly formatted and works just fine as well.

┌──[[email protected]][~/Documents]
└──╼  ╼ $ cat testingout.c
#include <unistd.h>
#include <stdio.h>
 
int
main (int argc, char **argv, char **env)
{
  int STDIN_PIPE[2];
  int STDOUT_PIPE[2];
 
  pipe (STDIN_PIPE);
  pipe (STDOUT_PIPE);
  pid_t pid = fork ();
  if (pid == 0)
    {
      char *path = "/path/to/binary";
      char *args[2];
      args[0] = path;
      args[1] = NULL;
      close (STDIN_PIPE[1]);
      close (STDOUT_PIPE[0]);
      dup2 (STDIN_PIPE[0], STDIN_FILENO);
      dup2 (STDOUT_PIPE[1], STDOUT_FILENO);
      execve (path, args, env);
    }
  else
    {
      char buf[128];
      close (STDIN_PIPE[0]);
      close (STDOUT_PIPE[1]);
      while (read (STDOUT_PIPE[0], buf, 1))
	write (1, buf, 1);
    }
}

Unwanted whitespace is very annoying if there are 1000 spaces after a line,. but this can be easily fixed.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.