add data to text file c# - AccountingEssaywritercsClub

add data to text file c#

This page may be out of date. Submit any pending changes before refreshing this page.
Hide this message .

C (programming language)

Programming Languages

Computer Programming

How can I write a c program to create a file?

7 Answers

Abdul Rossin

Abdul Rossin , Software Engineer

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows:

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file, and access mode can be read, write, append, etc.

The C program is:

int main()
FILE *fp;
return 0;

Inzamam Rahaman

Inzamam Rahaman , Programming for 4+ years

Similar to the way you would open a file: using fopen from stdio. The fopen function accepts a char pointer, mode, as its second argument. The mode to write to a file is "w".

Something like this should work:

#include <stdio.h>
#define FILE_NAME "text.txt"
int main() FILE* file_ptr = fopen(FILE_NAME, "w"); fclose(file_ptr); return 0;

fopen – C++ Reference goes into greater detail.

promoted by MongoDB

MongoDB Atlas: Built for your most sensitive workloads.
Automated MongoDB service built for the most sensitive workloads at any scale. Get started free.
Free Trial at

Rod Nussbaumer

Rod Nussbaumer , Wrote a program once, about 40 years ago. It was fun, so Ive kept doing it.

Use the open(), write(), close() functions, or the fopen(), fprintf(), fclose() families of standard C functions to open, write to, and close files. See the man pages for details and for links to related functions.

Khubaib Umer

Khubaib Umer , Linux Kernel Developer at Sublime Wireless Inc (2018-present)

Well this is a pretty stupid questions. You can find its answer by just searching for the exact same thing on google. However, let me break it down for you.

#include <stdio.h> // for io ops
#include <fcntl.h> // for file control

After this start your main method and create a file like this:

int fd = open("somefile" , O_CREAT);

Check value of fd. It should be greater than -1. If not file creation failed.

Elijah Tai

Elijah Tai , computational biology and bioinformatics student at University of Toronto

Theres a couple of ways of creating a file in C:

First, you could use standard output and redirections to use printf() from the stdio.h package to write to a file. Like so:

#include <stdio.h>
int main()	printf("This will write to a file.");	return 0

You can then at this point compile the program, and run it like so in the terminal:

./name_of_compiled_program > name_of_file.txt

What the above line of code is doing is that its taking what would normally be printed into your terminal as standard output, and redirecting that using the ">" character to a file named name_of_file.txt.

You can verify that the redirection has worked correctly by typing into your terminal:

cat name_of_file.txt

The output should say, "This will write to a file."

The second way of writing to a file is by using the stdio.h package again to open the file, write to the file, and then close the file.

Your program would look something like this:

#include <stdio.h>
int main()	// create a FILE typed pointer	FILE *file_pointer;	// open the file "name_of_file.txt" for writing	file_pointer = fopen("name_of_file.txt", "w");	// Write to the file	fprintf(file_pointer, "This will write to a file.");	// Close the file	fclose(file_pointer);	return 0;

Type into your terminal again:

cat name_of_file.txt

to verify that "This will write to a file." has in fact been printed into name_of_file.txt!

If you need more information on how stdio.h works, you can always type in "man stdio" into your terminal for documentation.

Hopefully this helps!

promoted by DigitalOcean

Starting a new project? Get started for free.
Scale your deployments with a flexible and predictable pricing model. Free for 60 days.
Learn More at

Peter Vanroose

Peter Vanroose , Professor at ABIS Training & Consulting (2004-present)

By issuing the “creat()” system call (directly or indirectly).

See e.g. creat(2 ) for a man page of the creat system call.


Geeks Classes
Write an Article

Geeks Classes

Quick Links for Python

Recent Articles
MCQ / Quizzes
Practice Problems
New Generation Language
Keywords , Set 1 Set 2
Explore More…
Variables,Expressions & Functions
Global and Local Variables
Type Conversion
Explore More…
Increment and Decrement Operator
Teranry Operator & Divison Operator
Logical and Bitwise Not Operators on Boolean
Any & ALL
Operator Functions Set 1 & Set 2
Data Types
Arrays Set 1 , Set 2
String Methods Set 1 , Set 2 , Set 3
String Template Class & String Formatting using %
List Methods Set 1 , Set 2 , Set 3
Tuples & Sets
Dictionary Methods Set 1 , Set 2
Explore More…
Control Flow
Loops and Control Statements
Counters & Accessing Counters
Iterators & Iterator Functions Set 1 , Set 2
Explore More…
Function Decorators
Returning Multiple Values
Yield instead of Return
Python Closures & Coroutine
Explore More…
Numeric Functions & Logarithmic and Power functions
Calender Functions Set 1 , Set 2
Complex Numbers Introduction & Important functions
Explore More…
Object Oriented Concepts
Class, Object and Members
Data Hiding and Object Printing
Inheritance, Subclass and super
Class method vs static method & Class or Static Variables
Explore More…
Exception Handling
Exception Handling
User-Defined Exceptions
Built-in Exceptions
Libraries and Functions
Numpy Set 1 , Set 2
Get and Post
import module & reload module
Collection Modules Deque , Namedtuple & Heap
Explore More…
Machine Learning with Python
Classifying data using Support Vector Machines(SVMs) in Python
K means Clustering
How to get synonyms/antonyms from NLTK WordNet in Python?
Explore More…
Sql using Python & MongoDB and Python
Json formatting & Python Virtual environment
Metaprogramming with Metaclasses in Python
Python Input Methods for Competitive Programming
Explore More…
Applications and Projects
Creating a proxy webserver Set 1 , Set 2
Send Messsage to FB friend
Twitter Sentiment Analysis & Whatsapp using Python
Desktop Notifier & Junk File Organizer
Explore More…

Reading and Writing to text files in Python

Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language,0s and 1s).

  • Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
  • Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine understandable binary language.

In this article, we will be focusing on opening, closing, reading and writing data in a text file.

File Access Modes

Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once its opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.

  1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
  2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
  3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
  4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
  5. Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
  6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.

Opening a File

It is done using the open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed.

# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile.txt","a")
# store its reference in the variable file1
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2

Closing a file

close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode.


# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")

Writing to a file

There are two ways to write in a file.

  1. write() : Inserts the string str1 in a single line in the text file.
  2. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert multiple strings at a single time.
    File_object.writelines(L) for L = [str1, str2, str3] 

Reading from a file

There are three ways to read data from a text file.

  1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.[n])
  2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
  3. readlines() : Reads all the lines and return them as each line a string element in a list.

Note: ‘\n’ is treated as a special character of two bytes

# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print "Output of Read function is "
# seek(n) takes the file handle to the nth
# bite from the beginning.
print "Output of Readline function is "
print file1.readline()
# To show difference between read and readline
print "Output of Read(9) function is "
print "Output of Readline(9) function is "
print file1.readline(9)
# readlines function
print "Output of Readlines function is "
print file1.readlines()


Output of Read function is
This is Delhi
This is Paris
This is London
Output of Readline function is
Output of Read(9) function is
Output of Readline(9) function is
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending to a file

# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1 = open("myfile.txt","r")
print "Output of Readlines after appending"
print file1.readlines()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()


Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']

Related Article :
File Objects in Python

This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes

Recommended Posts:

  • File Handling in Python
  • File Objects in Python
  • Using else conditional statement with for loop in python
  • Working with csv files in Python
  • Serial Sort v/s Parallel Sort in Java
  • Monkey Patching in Python (Dynamic Behavior)
  • Python Variables
  • Python | Pandas DataFrame.nsmallest()
  • Python | Pandas dataframe.drop_duplicates()
  • Python | Pandas DataFrame.nlargest()

( Login to Rate)

Average Difficulty : 1.5/5.0
Based on 4 vote(s)

User Actions









Writing code in comment? Please use , generate link and share the link here.

Trending Content

Python List , Set , Tuple & Dictionary

Number Theory

Set to Array in Java


School Programming

Longest Repeated Subsequence
Longest Palindromic Subsequence
Detect a negative cycle.
Reverse a linked list

Most Visited Posts
Top 10 Algorithms and Data Structures for Competitive Programming
Top 10 algorithms in Interview Questions
How to begin with Competitive Programming?
Step by Step Guide for Placement Preparation
How to prepare for ACM-ICPC?
Insertion Sort ,
Binary Search ,
QuickSort ,
MergeSort ,

Popular Categories
Interview Experiences
Advanced Data Structures
Dynamic Programming
Greedy Algorithms
Pattern Searching
Divide & Conquer
Geometric Algorithms
Analysis of Algorithms
Mathematical Algorithms
Randomized Algorithms
Game Theory
Statistical Algorithms


Advanced Data Structure
Bit Magic
Computer Networks
CPP Functions
C Quiz
Dynamic Programming
Interview Experiences
Java-lang package
Java – util package
Linked List
QA – Placement Quizzes
QA – Placement Quizzes
School Programming
Technical Scripter
Web Technologies