Get string from file

Monday, August 3rd, 2009

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE *fp;
  char str[128];

  if((fp = fopen(argv[ 1 ], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  while(!feof(fp)) {
    if(fgets(str, 126, fp)) 
        printf("%s", str);
  }

  fclose(fp);

  return 0;
}

           
       

Python object persistence for dictionary like object

Thursday, July 9th, 2009

import shelve

s = shelve.open(‘data‘)

s['key'] = range(4)

print s['key']               

s['key'].append(‘more‘)       

print s['key']                    

x = s['key']              

x.append(‘more‘)       

s['key'] = x              

print s['key']            

           
       

Demonstrate seekg().

Monday, July 6th, 2009

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
  char ch;

  if(argc!=3) {
    cout << "Usage: LOCATE <filename> <loc>\n";
    return 1;
  }

  ifstream in(argv[1], ios::in | ios::binary);

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  in.seekg(atoi(argv[2]), ios::beg);

  while(!in.eof()) { 
    in.get(ch);
    cout << ch;
  }

  in.close();

  return 0;
}

           
       

Reads files and displays them on the screen: use EOF

Wednesday, June 24th, 2009

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE *fp;
  char ch;

  if(argc!=2) {
    printf("You forgot to enter the filename.\n");
    exit(1);
  }

  if((fp=fopen(argv[1], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  ch = getc(fp);   /* read one character */

  while (ch!=EOF) {
    putchar(ch);  /* print on screen */
    ch = getc(fp);
  }

  fclose(fp);

  return 0;
}