Save a string to a file

From CodeCodex

It's quite common to have a string in memory that needs to be saved as a text file. Below are implementations to store a string (or similar) object as a file on the local file system.

Contents

[edit] Implementations

[edit] C

Use this source code to save a string to a file in C:


FILE *f;
char buff[10];
scanf("%s",&buff);
f = fopen ("path/to/file.ext", "w");
fprintf (f, "%s", buff);
fclose (f);

[edit] C++

Use this source code to save a string to a file in C++:


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

std::string s="hello world\n";
std::ofstream os("filename.txt");
if (!os) { std::cerr<<"Error writing to ..."<<std::endl; } else {
        os << s;
}
// Note: file is automatically closed, when current scope is left

[edit] Common Lisp

 (with-open-file (stream "filename.txt" :direction :output)
   (format stream "Your string here."))

[edit] Haskell


main = writeFile "filename.txt" "Your string here."

[edit] Java

Use this source code to save a string to a file in Java:


import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileWriter;
...
public static void saveTextFile(String contents, File file) throws IOException {
        PrintWriter out = new PrintWriter(new FileWriter(file));
        out.print(contents);
        out.close();
}

[edit] Objective-C


[myString writeToFile:filename atomically:YES];

[edit] OCaml


# let save file string =
let channel = open_out file in
output_string channel string;
close_out channel;;
val save : string -> string -> unit = <fun>

For example:

# save "foo" "bar\n";;
- : unit = ()
$ cat foo
bar

The Micmatch library provides a function which does this directly (Micmatch.Text.save):

# open Micmatch;;
# Text.save "foo" "bar\n";;
- : unit = ()

[edit] Perl

Use this source code to save a string to a file in Perl:


use File::Slurp qw(write_file);
write_file('filename', $string);

[edit] PHP

Use this source code to save a string to a file in PHP 5.x and above:


file_put_contents('file.name', 'file contents');

PHP 4.x and below:


$fh = fopen('file.name', 'w');
fputs($fh, 'file contents');
fclose($fh);

[edit] Python

Use this source code to save a string to a file in Python:


def save(filename, contents):
    fh = open(filename, 'w')
    fh.write(contents)
    fh.close()

save('file.name', 'some stuff')

[edit] Ruby

File.open(filename, 'w') do |f|
  f.write(myString)
end

[edit] Seed7

The "getf.s7i" library contains the function putf to write a string to a file:

putf("filename", string);

The definition of putf in the "getf.s7i" library is:

const proc: putf (in string: file_name, in string: stri) is func
  local
    var file: work_file is STD_NULL;
  begin
    if stri <> "" then
      work_file := open(file_name, "w");
      if work_file <> STD_NULL then
        write(work_file, stri);
        close(work_file);
      end if;
    end if;
  end func;

[edit] Tcl

proc text_save {filename string} {
  set f [open $filename w]
  fconfigure $f -encoding utf-8 -eofchar {} -translation lf
  puts -nonewline $f $string
  close $f
}

text_save foo bar\n

[edit] Visual Basic

Use this source code to save a string to a file in Visual Basic (VB):


sub SaveTextToFile(sText As String, sFileName As String)

Dim IFnum As Long

IFnum = FreeFile                      ' Get the next available file number

Open sFileName For Output As IFnum    ' Open file for write & create if it does not exist
Print #IFnum, sText                   ' Write string to file number
Close IFnum                           ' Close the file
end sub

SaveTextToFile("Some text I want to save", "c:\test.txt")

[edit] See also

Category:String