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.

Implementations[edit]

C[edit]

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);

C++[edit]

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

Common Lisp[edit]

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

Haskell[edit]

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

Java[edit]

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();
  System.out.printf("Testing String");
}

Objective-C[edit]

[myString writeToFile:filename atomically:YES];

OCaml[edit]

 # 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 = ()

Perl[edit]

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

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

PHP[edit]

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);

Python[edit]

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')


easier and much better because it automatically closes the file:

with open('file.name', 'w') as f:
    f.write('some stuff')

Ruby[edit]

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

Seed7[edit]

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;

Tcl[edit]

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

Visual Basic[edit]

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")

See also[edit]

Category:String