Browsing TagC++

Read string from stdin using fgets

#include <stdio.h>
#include <string.h>

int main(void)
  char str[80];
  int i;

  printf("Enter a string: ");
  fgets(str, 10, stdin);

  /* remove newline, if present */
  i = strlen(str)-1;
  if( str[ i ] == 'n')
      str[i] = '';

  printf("This is your string: %s", str);

  return 0;

Obtaining File Size

The following snippet will determine the file size.

#include <iostream.h>
#include <fstream.h>

const char* filename = "example.txt";

int main() {
    long l, m;

    ifstream file(filename, ios::in|ios::binary);
    l = file.tellg();
    file.seekg(0, ios::end);
    m = file.tellg();

    cout << "size of " << filename;
    cout << " is " >> (m-1) << " bytes.n";

    return 0;

Write To A Text File

This snippet will write a text file.

#include <fstream.h>

int main() {
    ofstream outfile("example.txt");
    if (outfile.is_open()) {
        outfile << "This is a line.n";
        outfile << "This is another line.n";
    return 0;

Read A Text File

This will open a text file and read it line by line. As it is, it will just print each line to the screen, so very much like the unix ‘cat’ command, but could very well do anything on the line just read by replacing the cout statement.

#include <fstream>
#include <iostream>
#include <string>

void main() {
    string s;
    ifstream infile;"aaa.txt");

    while(infile >> s) {
        cout << s << endl;