Read and Write a String from Text File

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

let fileURL = dir.appendingPathComponent(file)

//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}

//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"

//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}

Read File:

private String readFromFile(Context context) {

String ret = "";

try {
InputStream inputStream = context.openFileInput("config.txt");

if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}

inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}

return ret;
}

How to read a text file into a string variable and strip newlines?

You could use:

with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')

Or if the file content is guaranteed to be one-line

with open('data.txt', 'r') as file:
data = file.read().rstrip()

Perl read and write text file with strings

If what you want is a counter of names in a hash, then I got you, buddy!

I won't attempt the rest of the code because you are checking a folder of records
that I don't have access to so I can't trouble shoot anything more than this.

I see one of your problems. Look at this:

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say'; # Really like using say instead of print because no need for newline.

my $file = 'input_file.txt';
my $fh; # A filehandle.

my %hash;
my $people;
my $country;
my $line;
unless(open($fh, '<', $file)){die "Could not open file $_ because $!"}

while($line = <$fh>)
{
($people, $country) = split(/\s{2,}/, $line); # splitting on at least two spaces

say "$people \t $country"; # Just printing out the columns in the file or people and Country.

$hash{$people}++; # Just counting all the people in the hash.
# Seeing how many unique names there are, like is there more than one Cindy, etc ...?
}

say "\nNow I'm just sorting the hash of people by names.";

foreach(sort{$a cmp $b} keys %hash)
{
say "$_ => $hash{$_}"; # Based on your file. The counter is at 1 because nobody has the same names.
}

Here is the output. As you can see I fixed the problem by splitting on at least two white-spaces so the country names don't get cut out.

Andrew   UK

Cindy China

Rupa India

Gordon Australia

Peter New Zealand

Andrew United States

Now I'm just sorting the hash of people by names.
Andrew => 2
Cindy => 1
Gordon => 1
Peter => 1
Rupa => 1

I added another Andrew to the file. This Andrew is from the United States
as you can see. I see one of your problems. Look at this:

my ($people) = split("", $line);

You are splitting on characters as there is no space between those quotes.
If you look at this change now, you are splitting on at least one space.

 my ($people) = split(" ", $line);

Reading both string and integer from a text file

If the file is in exactly that format, you can use scanf() easily. Here's some code to get you started; I haven't tested this and you need to fill in a few missing things.

#include <ctypes.h>  // for isspace()
#include <stdio.h> // for scanf(), getchar(), and EOF

char c2d[MAX_LINES][MAX_LENGTH_STRING_PER_LINE];
char *pstr;
float f2d[MAX_LINES][6]; // 6 floats per line
float *p;
int c, current_line_number;
char ch;
FILE *input;

input = fopen(...);
if (!input)
... handle the error

for (current_line_number = 0; ; ++current_line_number)
{
// handle each line of input

// first read 6 float values
p = f2d + current_line_number;
c = fscanf(input, "%f %f %f %f %f %f", p + 0, p + 1, p + 2, p + 3, p + 4, p + 5);
if (c != 6)
... handle the error here

// next grab string; stop at '<' or end of line or EOF
pstr = c2d + current_line_number;
for (;;)
{
ch = fgetc(input);
if (ch == EOF || ch == '<' || ch == '\n')
{
*pstr = '\0';
break;
}
*pstr++ = ch;
}
if (ch == '<')
{
// char was '<' so throw away rest of input line until end of line
for (;;)
{
if (ch == EOF || ch == '\n')
break;
ch = fgetc(input);
}
}
for (;;)
{
// eat up any white space, including blank lines in input file
if (ch == EOF || !isspace(ch))
break;
ch = fgetc(input);
}
// once we have hit end of file we are done; break out of loop
if (ch == EOF)
break;
}

fclose(input);

I didn't use scanf() to read the string at the end of the line because it stops when it hits white space, and your string values have spaces in them.

If the input file isn't always six float values, you will need to write code to call scanf() one float at a time until you hit something that doesn't parse as a float, and you will need to make the array of floats wide enough to handle the largest number of floats you will permit per line.

Good luck.

How to read and write a text file in Flutter

Setup

Add the following plugin in pubspec.yaml:

dependencies:
path_provider: ^1.6.27

Update the version number to whatever is current.

And import it in your code.

import 'package:path_provider/path_provider.dart';

You also have to import dart:io to use the File class.

import 'dart:io';

Writing to a text file

_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}

Reading from a text file

Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}

Notes

  • You can also get the path string with join(directory.path, 'my_file.txt') but you need to import 'package:path/path.dart'.
  • Flutter's Official Documentation of Reading and Writing Files
  • This works for iOS, Android, Linux and MacOS but not for web.

How to write and read (including spaces) from text file

I'm guessing the space in "some string" is the problem. fscanf() reading a string using %s stops at the first whitespace character. To include spaces, use something like:

fscanf(fp, "%d\t%[^\n\t]\t%[^\n\t]", &t->num, &t->string1, &t->string2);

See also a reference page for fscanf() and/or another StackOverflow thread on reading tab-delimited items in C.

[EDIT in response to your edit: You seem to also have a problem with the arguments you're passing into fscanf(). You will need to post the declarations of t->string1 to be sure, but it looks like string1 is an array of characters, and therefore you should remove the & from the fscanf() call...]



Related Topics



Leave a reply



Submit