Anonymous user
Append a record to the end of a text file: Difference between revisions
Append a record to the end of a text file (view source)
Revision as of 15:47, 12 September 2011
, 12 years agoGrammar fixes, remove distracting italics, don't restrict tables to checkboxes (we have {{yes}}, {{no}}, and {{maybe}}), +Java (incomplete)
m (if possible - provide an actual code example - possibly using file/record locking - to guarantee correct concurrent appends.) |
(Grammar fixes, remove distracting italics, don't restrict tables to checkboxes (we have {{yes}}, {{no}}, and {{maybe}}), +Java (incomplete)) |
||
Line 2:
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of
'''Task:'''
Given a two
* Write
** Ideally these records will have named fields of various types.
* Close the file, then reopen the file for append.
** '''Append'''
** Take appropriate care to avoid concurrently overwrites from another job.
* Open the file and demonstrate the new record has indeed written to the end.
Finally:
Alternatively: If the language's appends can not guarantee its writes will '''always'''
=={{header|Java}}==
{{incomplete|Java|It does not have a table of append record capabilities.}}
<lang java>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Append{
public static void main(String[] args){
try{
System.out.println("Pre-loading file...");
//the "true" here is for autoflush
PrintWriter out =
new PrintWriter(new FileWriter("passwd"), true);
out.println("user1 password1");
out.println("user2 password2");
out.close();
showFile("passwd");
System.out.println("\nAppending new line to file...");
//the first "true" is for append, the second is for autoflush
out = new PrintWriter(new FileWriter("passwd", true), true);
out.println("user3 password3");
out.close();
showFile("passwd");
}catch(IOException e){
System.err.println("Error in writing file: " + e.getMessage());
}
}
private static void showFile(String filename){
try{
BufferedReader in = new BufferedReader(new FileReader(filename));
while(in.ready()){
System.out.println(in.readLine());
}
}catch(FileNotFoundException e){
System.err.println("File " + filename + " not found.");
}catch(IOException e){
System.err.println("Error in reading file: " + e.getMessage());
}
}
}</lang>
Output:
<pre>Pre-loading file...
user1 password1
user2 password2
Appending new line to file...
user1 password1
user2 password2
user3 password3</pre>
=={{header|Python}}==
<!-- ☐ ☑ ☒ -->
|