C (programming language)
How can I write a c program to create a file?
, 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:
#include<stdio.h> int main() FILE *fp; fp=fopen("file.txt","w"); fclose(fp); return 0;
, 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.
, Wrote a program once, about 40 years ago. It was fun, so Ive kept doing it.
, 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.
, 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:
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:
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!
, 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.
|MCQ / Quizzes|
|New Generation Language|
|Keywords , Set 1 Set 2|
|Variables,Expressions & Functions|
|Global and Local Variables|
|Increment and Decrement Operator|
|Teranry Operator & Divison Operator|
|Logical and Bitwise Not Operators on Boolean|
|Any & ALL|
|Operator Functions Set 1 & Set 2|
|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|
|Loops and Control Statements|
|Counters & Accessing Counters|
|Iterators & Iterator Functions Set 1 , Set 2|
|Returning Multiple Values|
|Yield instead of Return|
|Python Closures & Coroutine|
|Numeric Functions & Logarithmic and Power functions|
|Calender Functions Set 1 , Set 2|
|Complex Numbers Introduction & Important functions|
|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|
|Libraries and Functions|
|Numpy Set 1 , Set 2|
|Get and Post|
|import module & reload module|
|Collection Modules Deque , Namedtuple & Heap|
|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?|
|Sql using Python & MongoDB and Python|
|Json formatting & Python Virtual environment|
|Metaprogramming with Metaclasses in Python|
|Python Input Methods for Competitive Programming|
|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|
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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") file1.close()
Writing to a file
There are two ways to write in a file.
- write() : Inserts the string str1 in a single line in the text file.
- 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.
- read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
- 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.
- 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.writelines(L) file1.close() #to change file access modes file1 = open("myfile.txt","r+") print "Output of Read function is " print file1.read() print # seek(n) takes the file handle to the nth # bite from the beginning. file1.seek(0) print "Output of Readline function is " print file1.readline() print file1.seek(0) # To show difference between read and readline print "Output of Read(9) function is " print file1.read(9) print file1.seek(0) print "Output of Readline(9) function is " print file1.readline(9) file1.seek(0) # readlines function print "Output of Readlines function is " print file1.readlines() print file1.close()
Output of Read function is Hello This is Delhi This is Paris This is London Output of Readline function is Hello Output of Read(9) function is Hello Th Output of Readline(9) function is Hello 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"] file1.close() # Append-adds at last file1 = open("myfile.txt","a")#append mode file1.write("Today \n") file1.close() file1 = open("myfile.txt","r") print "Output of Readlines after appending" print file1.readlines() print file1.close() # Write-Overwrites file1 = open("myfile.txt","w")#write mode file1.write("Tomorrow \n") file1.close() file1 = open("myfile.txt","r") print "Output of Readlines after writing" print file1.readlines() print file1.close()
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 contribute.geeksforgeeks.org 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.
- 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()
Average Difficulty : 1.5/5.0
Based on 4 vote(s)
Writing code in comment? Please use ide.geeksforgeeks.org , generate link and share the link here.
Python List , Set , Tuple & Dictionary
|Set to Array in Java|
BFS , DFS
|Longest Repeated Subsequence|
|Longest Palindromic Subsequence|
|Detect a negative cycle.|
|GATE CS Notes|
|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 ,
|Advanced Data Structures|
|Divide & Conquer|
|Analysis of Algorithms|
Java – util package
QA – Placement Quizzes
QA – Placement Quizzes