Tag Archive for read

Read arithmetic binary data using fstreams #2

unsigned short fread_unsigned_short(ifstream &input_file) { //note that the ifstream is passed by reference
    unsigned short num;
    //the cast reinterpretation is very importnant
    input_file.read(reinterpret_cast < char * > (&num),sizeof(unsigned short));
    return num;
}

ifstream input_data;
input_data.open("input.dat",ios::in | ios::binary); //note the modifiers that denote both input file and binary mode
unsigned short num=fread_unsigned_short(input_data);

/*
The above function can be generalized to any numeric datatype like integers, floats e.t.c.
just replace the type 'unsigned short' with the wanted type
*/

source

Read and Write User Preferences

//
//  SetPrefsAppDelegate.h
//
#import <UIKit/UIKit.h>
 
@interface SetPrefsAppDelegate : NSObject <UIApplicationDelegate> 
{
  BOOL        saveUsername;
  NSInteger   preferredIndexInTabbar;
  UIWindow    *window;
}
 
@property (nonatomic, retain) IBOutlet UIWindow *window;
 
@end


//  SetPrefsAppDelegate.m
//
#import "SetPrefsAppDelegate.h"
#import "Preferences.h"
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// App Delegate implementation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@implementation SetPrefsAppDelegate
 
@synthesize window;
 
/*------------------------------------------------------
* Read preferences from system
*-----------------------------------------------------*/
-(void) loadPreferences
{ 
  saveUsername = [Preferences shouldSaveUsername];
  preferredIndexInTabbar = [Preferences startupTab]; 
}
 
/*------------------------------------------------------
* Application startup code
*-----------------------------------------------------*/
- (void)applicationDidFinishLaunching:(UIApplication *)application 
{   
  // Load user preferences (notice the default values the first time through)
  [self loadPreferences];
 
  // Show the current values of the preferences
  NSLog(@"Save user preferences: %s", saveUsername == YES ? "Yes" : "No");
  NSLog(@"Preferred startup tab: %d", preferredIndexInTabbar);
 
  // This is a little contrived, but you get the point...
  BOOL saveUname = YES;
  NSInteger index = 3;
 
  // Write new values to the sytem
  [Preferences setPreferences:saveUname startupTab:index];
 
//  NSLog(@"Home: %s", NSHomeDirectory());
//  NSLog(@"Home: %@", NSHomeDirectory());
 
  // Override point for customization after application launch
  [window makeKeyAndVisible];
}
 
- (void)dealloc 
{
  [window release];
  [super dealloc];
}
 
@end

source

Read a web page with Java

public String readURL(String address) throws Exception
{
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
InputStream in = conn.getInputStream();
int read;

while((read = in.read(buff)) != -1)
out.write(buff, 0, read);

return out.toString().replaceAll("[s]+", " ");
}

source

Read a file line by line

#!/bin/sh
while read LINE
do
echo "processing $LINE"
done < your_input_file

An example of your_input_file would be:

one
two
three

Each line in your_input_file will be read into LINE.

source

write and read XML

<?php
session_start();

$_SESSION['arrConfig'];


$docConfigXML = new DOMDocument;
$docConfigXML->preserveWhiteSpace = FALSE;
$docConfigXML->load( 'resources/xml/config.xml' );

$_SESSION['arrConfig']['fax'] = trim($docConfigXML->getElementsByTagName("fax")->item(0)->getAttribute('value'));
$_SESSION['arrConfig']['phone'] = trim($docConfigXML->getElementsByTagName("phone")->item(0)->nodeValue);

echo $_SESSION['arrConfig']['fax'];
echo "<br />";
echo $_SESSION['arrConfig']['phone'];

$strConfigXML = "";


$fax 	= "702-555-1faxxx";
$phone 	= '702-555-phone';

$strConfigXML =
<<<END
<?xml version="1.0" encoding="utf-8"?>
<config>
<fax value='$fax' />
<phone>
$phone
</phone>
</config>
END;

$file = "resources/xml/config.xml";

writeFile($file,$strConfigXML);

function writeFile($file,$strFileContent)
{
$fh = fopen($file, 'w' ) or die ("can't create file");
fwrite($fh, $strFileContent);
fclose($fh);
}
?>

source

Dump a file to the terminal, starting at some line number

tail -n+99 foo.txt | more

source

parse URI object, and fetch response from it, in one step

require "open-uri"

uri="http://www.ruby-lang.org/en/"

html=URI.parse(uri).read # string representation is the response body

http_headers=URI.parse(uri).read.meta # this hash's keys are also accessible as OpenURI instance methods, e.g. html.content_type

source

Read Directory

1.
function dodir($dir) {
2.
if ($handle = opendir($dir)) {
3.
$files = array();
4.
while (false !== ($file = readdir($handle))) {
5.
if ($file != "." && $file != "..") {
6.
$files[] = $file;
7.
}
8.
}
9.
closedir($handle);
10.
}
11.
return $files;
12.
}

source

Sun SPOT read bundled file as resource

public class GetAppPropertiesSpotApp extends MIDlet {
protected void startApp() throws MIDletStateChangeException {
String nameOfFile=this.getAppProperty("NameOfFile");
System.out.println("NameOfFile=" + nameOfFile);
InputStream is = getClass().getResourceAsStream(nameOfFile);
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line=br.readLine())!=null) {
System.out.println("line=" + line);
}

}

protected void pauseApp() {}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}

}

source