This blog is under construction

Sunday, 28 July 2013

C program to delete all blank lines in a file

Write a C program to delete all blank lines in a file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main(int argc, char **argv) {
        FILE *fp1, *fp2;
        char str[MAX];

        /* open the input file in read mode */
        fp1 = fopen(argv[1], "r");

        /* incase if file pointer is null */
        if (!fp1) {
                printf("Unable to open input file!!\n");
                return 0;
        }

        /* open another file in write mode */
        fp2 = fopen(argv[2], "w");

        if (!fp2) {
                printf("Unable to open the file to write\n");
                return 0;
        }

        /* copy the contents of file 1 to file 2 except all blank lines */
        while (!feof(fp1)) {
                fgets(str, MAX, fp1);
                if (strcmp(str, "\n") == 0) {
                        continue;
                }
                fputs(str, fp2);
                strcpy(str, "\0");
        }

        /* close both the files */
        fclose(fp1);
        fclose(fp2);

        /* remove in the source file(with blank lines) */
        remove(argv[1]);
        /* rename output file to source file name */
        rename(argv[2], argv[1]);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -

  think of it, dream of it, live on that idea. Let 

  the brain, muscles, nerves, every part of your 

  body, be full of that idea, and just leave every 

  other idea alone. This is the way to success.

  jp@jp-VirtualBox:~/$ ./a.out data.txt output.txt

  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.






SEE ALSO

    No comments:

    Post a Comment