Perl script to add Header to files

The following script will add text to the beginning of files.

Donwload here. perlheader.pdf

This is done in three steps

1) This script copies the contents of a file to local variable by slurping.

2) The necessary text that needs to be added at the beginning of the file is added.

3) Then the original contents of the file are added using the local variable.

 

 

#!/usr/bin/perl

# Filename: header.pl

# Author : A.G.Raja

# Website : agraja.wordpress.com

# License : GPL

# pass files as arguments to this script

# this script will add the header text

use strict;

use warnings;

sub addheader{

my($infile,$header)=@_;

my $text = do { local( @ARGV, $/ ) = $infile ; <> } ;

open(FILE,”>$infile”);

print FILE $header;

print FILE $text;

close FILE

}

my $argnum;

foreach $argnum (0 .. $#ARGV){

my $infile = $ARGV[$argnum];

# Edit line below to change header text

my $header = “Header line 1nHeader line 2nHeader line 3n”;

&addheader($infile,$header);

}

# chmod +x header.pl

# ./header.pl *.txt

 

Donwload here. perlheader.pdf

C++ File Operations

// file_write.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile (“example.txt”);
if (myfile.is_open())
{
myfile << “This is a line.\n”;
myfile << “This is another line.\n”;
myfile.close();
}
else cout << “Unable to open file”;
return 0;
}
// g++ file_write.cpp
// file_read.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile (“example.txt”);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”<<endl;
return 0;
}
//g++ file_read.cpp
Download here.
cpp_file_operations.doc

C File Operations

////////   file_operations.c  ////////
 #include <stdio.h>
 int main(void)
 {
 char temp[100];
 FILE *write_to_file = fopen("file.txt","w");
 fprintf(write_to_file,"%08x",0xC12E3A4);
 fclose(write_to_file);
 FILE *read_from_file = fopen("file.txt", "rb");
 fscanf(read_from_file,"%s",temp);
 printf("String read from file=%sn",temp);
 fclose(read_from_file);
 return 0;
 }

[raja@AGRAJA ~]$ gcc -Wall file_operations.c
[raja@AGRAJA ~]$ ./a.out

String read from file=0c12e3a4

Download here:

c_file_operations.doc