Jump to content


Check out our Community Blogs

DarkLordoftheMonkeys

Member Since 22 Oct 2009
Offline Last Active Jul 15 2010 11:26 AM
-----

Topics I've Started

Controlling print jobs in Unix with Postscript

18 May 2010 - 10:25 AM

Postscript is the programming language used to control the majority of printers for personal computers. It gives you more control over how a text file will appear when printed, including the typeface, whether to print in portrait or landscape, how far to indent, etc. The key commands for Unix printing are lp, lpr, lpstat, and enscript.


Using lp and lpstat:

The command to send a file to the printer in Unix is lp (lpr in some systems). It can be used for both text and binary files (such as images). To print using lp, you need to know the name of the destination printers you can use, that is, what printers the system recognizes (if a printer is not recognized, you may have to configure it manually). To do this, type:

lpstat
...In the terminal. This should show some information, including the name of the main printer.

lp -d printer_name filename
This is the standard format for the lp command. The option -d means the destination printer.


Using enscript:

enscript is the Unix command to convert a text file to PostScript automatically. You don't need to know PostScript, just this command and its options. The bare-bones format of the enscript command is:

enscript -o output-file.eps textfile
The filename after -o is the file to send the PostScript code to (the PostScript file). The extension for a PostScript file is .eps.

Other options:

-f - controls the typeface used when printing the file. The name of the typeface consists of the font name followed by a number for the size, as in Courier10 (the default).

-r - print in landscape format

-R - print in portrait format

-b - controls the heading to put on the file. The default is the filename and the date.

-F - select a font for the header text.

-i - number of characters to indent

-j - print borders around the pages

Example:

enscript -r -b "2010 Calendar" -f Monaco9 -i 5 -o calendar.eps calendar.txt

For more information on enscript's options, see the man page.


Printing PostScript files:

lp can be used for a PostScript file just like an ordinary file. It will print the output of the PostScript program, not the code itself.

Some systems (such as Mac OS X) will convert a PostScript file to a PDF when it is opened in the GUI. This makes it possible to print it without using the command line or lp.

I need advice on optimizing memory usage.

10 April 2010 - 08:48 AM

I'm using a linked list for my program. I wrote a function to read lines from a file and store the lines in nodes of the linked list.

Here's the important code:

struct line {
    char *linetext;
    int linenumber;
    struct line *nextline;
};
#define NEXTLINE (*((*lineptr).nextline))
int *numsOfChars( FILE *fp ){
    int numLines = linecount( fp );        
    int *lines = (int *) malloc( sizeof(int) );     // Declare int array.  Must use malloc because
    wchar_t ch;                                     // the address is returned by the function.
    for( int j = 0; j < numLines; j++ ){
        lines[j] = 0;
        while( (ch = fgetc( fp )) != '\n' ){    // For each line n, this goes until the nth 
            lines[j]++;                         // newline, effectively counting the characters
        }                                       // in the nth line until the newline.
    }
    rewind( fp );
    return lines;
}
Most importantly:

// This function reads another line and stores it in the linked list.
// Parameters: lineptr - pointer to the current line, numchars - array of character counts for each line, fp - file pointer
struct line *readLine( struct line *lineptr, int *numchars, FILE *fp ){
    // line number for next line
    int nextLineNum = (*lineptr).linenumber + 1;
    // allocate memory for next line
    (*lineptr).nextline = (struct line *) malloc( sizeof(struct line) );
    // set line number
    NEXTLINE.linenumber = nextLineNum;
    // string to read the line from the file into
    char *linec = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
    // read the line of the file into the string
    fgets( linec, (numchars[nextLineNum] + 1), fp );
    // const because strcpy takes a const as its second parameter
    const char *line2c = linec;
    // dynamically allocate NEXTLINE.linetext so it can be copied to
    NEXTLINE.linetext = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
    // copy to linetext
    strcpy( NEXTLINE.linetext, line2c );
    free( linec );
    return (*lineptr).nextline;
}

Without comments, if that makes it easier to read:

struct line *readLine( struct line *lineptr, int *numchars, FILE *fp ){
    int nextLineNum = (*lineptr).linenumber + 1;
    (*lineptr).nextline = (struct line *) malloc( sizeof(struct line) );
    NEXTLINE.linenumber = nextLineNum;
    char *linec = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
    fgets( linec, (numchars[nextLineNum] + 1), fp );
    const char *line2c = linec;
    NEXTLINE.linetext = (char *) malloc( sizeof(char) * (numchars[nextLineNum] + 1) );
    strcpy( NEXTLINE.linetext, line2c );
    free( linec );
    return (*lineptr).nextline;
}

How I called it:

curline = readLine( curline, numchars, fp );
This works fine for the first few lines, but after I get to about the fifth or sixth one, the linked list gets really huge and the program runs out of memory, resulting in a bus error. Is there any way I can fix this?

How do you make a dynamically allocated pointer to a static array in C?

08 April 2010 - 07:56 AM

I want to create a pointer to a static character array. The array has to be INT16_MAX characters long, so I would like to be able to get rid of it later in the program. The only way I can think of to do this is to dynamically allocate a pointer to it, using malloc. I tried:

char[INT16_MAX]  *strptr = (char[] *) malloc( sizeof(char[] *) );
and

char st[INT16_MAX] *strptr ...;
Neither of them works. What is the data type for a pointer to an array? I can't use char **, because the array has to be a fixed width. Otherwise the compiler won't let me read a line from a file into it and I get a segfault. Please don't tell me why the code I gave is wrong. I know perfectly well that it doesn't make sense; I just wanted to provide some examples to illustrate. You can ignore the malloc part. It really isn't important. All I want to know is how to make a pointer to a fixed width array so that I can deallocate the array later and not clog up memory.

Also, please no "You're not supposed to use INT16_MAX" or any of that ** that has nothing to do with the problem.

What is a non-aligned pointer?

04 April 2010 - 10:22 AM

Sometimes when I try to free a malloc'd pointer in a C program, I get a runtime error like this:

readlines(11487) malloc: *** error for object 0x1f2a: Non-aligned pointer being freed
*** set a breakpoint in malloc_error_break to debug
What does that mean?

Neat things you can do with Unix

09 March 2010 - 09:54 AM

Some of these are useful hacks, some are just amusing productivity killers. Most of them work on all shells, though if I'm not sure, I'll say so...

Hack #1: Change the prompt

The environment variable PS1 controls the prompt the shell gives you when it asks for a command. You can set it just like any other variable:

export PS1="\s-\v\$ "
The \s, \v, and \$ are escape sequences that represent strings to use for the prompt. This prompt would display the shell name followed by the version number, followed by a dollar sign.

Here are some of the escape sequences for the prompt:

\A - time of day (24-hour format)
\H - host name
\h - host name up to the first dot
\s - shell
\u - username
\v - version
\w - working directory
\W - trailing element of the working directory
\! - current command history number
\@ - time of day (12-hour format)
\$ - dollar sign

Note: The Z shell might use a different variable.


Hack #2: Reverse the text of a file

Typing "rev filename" will output the contents of a file, with each line reversed. You can create a backwards file using I/O redirection. This works on both Mac OS X and Linux. I don't know about other systems.

Hack #3: banner

A command created just for fun, present in Unix since the very early days (I learned about it from the 7th Edition Unix Manual).

banner -width "text"
Here's the banner I created by typing "banner -50 '/usr/bin/banner'":

            # 
            ####
               ####
                  ### 
                     ####
                        #### 
                           ### 
                              ####
                                 #### 
                                    ####
                                       ####
                                           ### 
                                             # 
                               # 
                ################ 
             ################### 
            #################### 
            #### 
            ###
            ###
             ##
               #               # 
            #################### 
            #################### 
            #################### 
            # 
            #####        ###
            #####      #######
             ##      ########## 
            ###      ######   ##
            ##      #####      # 
            #       #####      # 
            #      #####      ## 
            ##     #####     ###
             ##   ######   ##### 
             ##########    ##### 
               ###### 
            #                  # 
            #################### 
            #################### 
            #################### 
            #             ###
                            ## 
                             ## 
                             ###
                         ####### 
                         ####### 
                         #######
                              
            # 
            ####
               ####
                  ### 
                     ####
                        #### 
                           ### 
                              ####
                                 #### 
                                    ####
                                       ####
                                           ### 
                                             # 
            #                                # 
            ################################## 
            ################################## 
            ################################## 
               #            ##
             ##               ##
            ##                ##
            ##                ## 
            ###              ###
             #####        ######
              ################ 
                ############
                           
            #                  # 
            ####################      ### 
            ####################     ##### 
            ####################     #####
            # 
            #                  # 
            #################### 
            #################### 
            #################### 
            #               ##
                             ## 
                              ##
                              ## 
            #               #### 
            ####################
            ################### 
            ################
            # 
            # 
            ####
               ####
                  ### 
                     ####
                        #### 
                           ### 
                              ####
                                 #### 
                                    ####
                                       ####
                                           ### 
                                             # 
            #                                # 
            ################################## 
            ################################## 
            ################################## 
               #            ##
             ##               ##
            ##                ##
            ##                ## 
            ###              ###
             #####        ######
              ################ 
                ############
                           
                ### 
              ########
             ##########   ##### 
            ####    ####  ######
            ##        ##      ## 
            ##        ##       # 
             ##      ##       ## 
              ##################
            ###################
            ##################
            ## 
            #
            #                  # 
            #################### 
            #################### 
            #################### 
            #               ##
                             ## 
                              ##
                              ## 
            #               #### 
            ####################
            ################### 
            ################
            # 
            #                  # 
            #################### 
            #################### 
            #################### 
            #               ##
                             ## 
                              ##
                              ## 
            #               #### 
            ####################
            ################### 
            ################
            # 
                   ###### 
                ############ 
              ################ 
             #####   ##   ##### 
            ###      ##       ##
            #        ##        # 
            #        ##        # 
            #        ##       ##
             #       ##     ####
             ##      ##########
               ##    ########
                     #### 
            #                  # 
            #################### 
            #################### 
            #################### 
            #             ###
                            ## 
                             ## 
                             ###
                         ####### 
                         ####### 
                         #######
Hack #4: screen

screen is a Unix program that lets you have multiple windows open in the same console. When you enter screen by typing "screen", it brings up a window that gives you information about screen. screen has several keystrokes that you can use, all beginning with Ctrl+A. To add a new window, type Ctrl+A Ctrl+C, or if that doesn't work, Ctrl+A c (type those two keystrokes in succession). You can navigate between windows using keystrokes like Ctrl+A Ctrl+N (go to the next window) and Ctrl+A followed by a number (go to the numbered window). I'm still learning to use this, so I don't know much about it, but here are some of the commands:

Ctrl+A Ctrl+A - go to the last window open
Ctrl+A Ctrl+C - create a new window
Ctrl+A Ctrl+N - go to the next window
Ctrl+A N - go to the Nth window
Ctrl+A k - kill the current window
Ctrl+A " - prompt for which window to go to


Hack #5: Emacs games

Emacs is a great programming environment (the second best after Vim). It's also a great gaming environment. When in Emacs, you can type M-x to get to the games. On some systems (like my Mac), the Meta key is the Escape key. After you type this, you will get a prompt at the bottom of the screen. Enter the title of the game to play. Games include tetris, pong, blackbox, solitaire, dunnet, life, decipher, mpuz, 5x5, hanoi, lm, morse-region, and studlify-region.

Hack #6: Dumb terminal nostalgia

Ever wished you could go back to the days of teletypes and monochrome screens, with the PDP-11 and other ancient computers? Well now you can (sort of), by setting the environment variable TERM to "dumb". Enter this in the command line:

export TERM=dumb
Now the terminal is monochromatic, does not run full-screen apps correctly, and does not recognize escape sequences, just like an old dumb terminal. Kind of a stupid thing to do, but I thought it was kind of neat. To change back, just type "TERM=xterm-color" or whatever your default terminal is.

Hack #7: Scheduling tasks with crontab

crontab is used to edit the crontab file that configures cron, a daemon that runs tasks at scheduled times. Make sure you have EDITOR set to vi or emacs or whatever you use, as crontab will open the file in that editor. Here is most of what you need to know:

crontab -u myusername -e
The syntax for the crontab file is:

minute (0-59)     hour (0-23)     dayofmonth     month     dayofweek    command
To schedule something for all days, or all hours, you would have a * in that field.

Commands involving terminal output will not work.


Hack #8: Editor keybindings

You can use the keybindings of your favorite text editor by setting them with a very simple command.

set -o editor
If editor is vi, then when you press the escape key, you will go into vi command mode, where you can type 0 to go to the beginning of the line, dd to delete, etc.


Hack #9: hexdump

This is a command you can use to look inside a binary file and see its raw code, in hexadecimal. The command is:

hexdump -C filename
Hack #10: xeyes

An X-Window program that demonstrates cursor movement detection. A pair of eyes watches what you do and reports to the boss. Completely useless, but amusing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download