Tuesday, March 16, 2010

Blogger Code Formatter

Blogger is a wonderful place to write blogs and there are many code bloggers out there, who want to share their coding skills with the world! But, certainly there are some problems with blogger posting methods, for example, in a <pre> tag, it will ignore tabs, and it causes great problems with some operators like '<', '>' etcetera... So, we can easily write a simple program and use it easily as a code formatter for blogger. Here's an example:

#include <cstdio>

int main(int argc, char **argv) {
    FILE *in = fopen(argv[1], "r");
    FILE *out = fopen(argv[2], "w");
    char ch;
    if(argc < 3) {
        printf("Usage: $ %s <infile> <outfile>\n", argv[0]);
        return 1;
    if(in==NULL) {
        printf("file %s can't be opened.\n", argv[1]);
        return 2;
    if(out==NULL) {
        printf("file %s can't be opened.\n", argv[2]);
        return 3;
    while(fscanf(in, "%c", &ch)==1) {
        if(ch=='>') fprintf(out, "&gt;");
        else if(ch=='<') fprintf(out, "&lt;");
        else if(ch=='&') fprintf(out, "&amp;");
        else if(ch=='\t') fprintf(out, "    ");
        else fprintf(out, "%c", ch);
    printf("file %s was written succesfully.\n", argv[2]);
    return 0;


In windows, execute this with any compiler and grab the .exe file, paste it in your C:\WINDOWS\system32 folder. So, for example, if the file name is "blog.cpp", you will get "blog.exe", just paste it to your system32 folder. So now you can use it as a command in command prompt. If you like to format a file, say, "test.cpp", cd to the directory where "test.cpp" is, and to transform, the command is "blog test.cpp blog_test.cpp". Now just open the "blog_test.cpp" file and paste it in the <pre> tags.


Run it with g++, command: "g++ -o blog blog.cpp", and give enough permissions to the executable "blog", command: "chmod 777 blog". Now, we need to paste it in the "/bin" directory, but as it is write protected, we'll need to log in as root. To do this, write on prompt: "sudo nautilus", it will ask your password, and then an explorer will be opened, and now, just go to the "/bin" directory using it and paste the file. The usage is similar as stated in the Windows part.

Makes life a bit easier...

No comments:

Post a Comment