aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Data
  • Practices
  • Programming
  • Software

How Different Programming Languages Read And Write Data

  • Ackley Wyndam
  • September 2, 2021
  • 4 minute read

Every programming language has a unique way of accomplishing a task; that’s why there are so many languages to choose from.

In his article How different programming languages do the same thing, Jim Hall demonstrates how 13 different languages accomplish the same exact task with different syntax. The lesson is that programming languages tend to have many similarities, and once you know one programming language, you can learn another by figuring its syntax and structure.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

In the same spirit, Jim’s article compares how different programming languages read and write data. Whether that data comes from a configuration file or from a file a user creates, processing data on a storage device is a common task for coders. It’s not practical to cover all programming languages in this way, but a recent Opensource.com series provides insight into different approaches taken by these coding languages:

  • C
  • C++
  • Java
  • Groovy
  • Lua
  • Bash
  • Python

 

Reading and writing data

The process of reading and writing data with a computer is similar to how you read and write data in real life. To access data in a book, you first open it, then you read words or you write new words into the book, and then you close the book.

When your code needs to read data from a file, you provide your code with a file location, and then the computer brings that data into its RAM and parses it from there. Similarly, when your code needs to write data to a file, the computer places new data into the system’s in-memory write buffer and synchronizes it to the file on the storage device.

Here’s some pseudo-code for these operations:

  1. Load a file in memory.
  2. Read the file’s contents, or write data to the file.
  3. Close the file.
Read More  Real-Time Dynamic Authorization – An Introduction To OPAL

 

Reading data from a file

You can see three trends in how the languages in the Opensource.com series read files.

C

In C, opening a file can involve retrieving a single character (up to the EOF designator, signaling the end of the file) or a block of data, depending on your requirements and approach. It can feel like a mostly manual process, depending on your goal, but the general process is exactly what the other languages mimic.

FILE *infile;
int ch;infile = fopen(argv[1], “r”);do {
ch = fgetc(infile);
if (ch != EOF) {
printf(“%c”, ch);
}
} while (ch != EOF);fclose(infile);

You can also choose to load some portion of a file into the system buffer and then work out of the buffer.

FILE *infile;
char buffer[300];infile = fopen(argv[1], “r”);while (!feof(infile)) {
size_t buffer_length;
buffer_length = fread(buffer, sizeof(char), 300, infile);
}printf(“%s”, buffer);
fclose(infile);

C++

C++ simplifies a few steps, allowing you to parse data as strings.

std::string sFilename = “example.txt”;

std::ifstream fileSource(sFilename);
std::string buffer;

while (fileSource >> buffer) {
std::cout << buffer << std::endl;
}

 

Java

Java and Groovy are similar to C++. They use a class called Scanner to set up a data object or stream containing the contents of the file of your choice. You can “scan” through the file by tokens (byte, line, integer, and many others).

File myFile = new File(“example.txt”);

Scanner myScanner = new Scanner(myFile);
while (myScanner.hasNextLine()) {
String line = myScanner.nextLine();
System.out.println(line);
}

Read More  How To Install IntelliJ IDEA (Java IDE) In Ubuntu

myScanner.close();

 

Groovy

def myFile = new File(‘example.txt’)

def myScanner = new Scanner(myFile)
while (myScanner.hasNextLine()) {
def line = myScanner.nextLine()
println(line)
}

myScanner.close()

Lua

Lua and Python abstract the process further. You don’t have to consciously create a data stream; you just assign a variable to the results of an open function and then parse the contents of the variable. It’s quick, minimal, and easy.

myFile = io.open(‘example.txt’, ‘r’)

lines = myFile:read(“*all”)
print(lines)

myFile:close()

 

Python

f = open(‘example.tmp’, ‘r’)

for line in f:
print(line)

f.close()

 

Writing data to a file

In terms of code, writing is the inverse of reading. As such, the process for writing data to a file is basically the same as reading data from a file, except using different functions.

C

In C, you can write a character to a file with the fputc function.

<a href="http://www.opengroup.org/onlinepubs/009695399/functions/fputc.html"><span class="kw3">fputc</span></a><span class="br0">(</span>ch<span class="sy0">,</span> outfile<span class="br0">)</span><span class="sy0">;</span>

Alternately, you can write data to the buffer with fwrite.

<a href="http://www.opengroup.org/onlinepubs/009695399/functions/fwrite.html"><span class="kw3">fwrite</span></a><span class="br0">(</span>buffer<span class="sy0">,</span> <span class="kw4">sizeof</span><span class="br0">(</span><span class="kw4">char</span><span class="br0">)</span><span class="sy0">,</span> buffer_length<span class="sy0">,</span> outfile<span class="br0">)</span><span class="sy0">;</span>

C++

Because C++ uses the ifstream library to open a buffer for data, you can write data to the buffer, as with C (except with C++ libraries).

std<span class="sy4">::</span><span class="kw3">cout</span> <span class="sy1"><<</span> buffer <span class="sy1"><<</span> std<span class="sy4">::</span><span class="me2">endl</span><span class="sy4">;</span>

Java

In Java, you can use the FileWriter class to create a data object that you can write data to. It works a lot like the Scanner class, except going the other way.

FileWriter myFileWriter = new FileWriter(“example.txt”, true);
myFileWriter.write(“Hello world\n“);
myFileWriter.close();

Groovy

Similarly, Groovy uses FileWriter but with a slightly “groovier” syntax.

new FileWriter(“example.txt”, true).with {
write(“Hello world\n“)
flush()
}

Lua

Lua and Python are similar, both using functions called open to load a file, write to put data into it, and close to close the file.

myFile = io.open(‘example.txt’, ‘a’)
io.output(myFile)
io.write(“hello world\n“)
io.close(myFile)

Python

myFile = open(‘example.txt’, ‘w’)
myFile.write(‘hello world’)
myFile.close()

 

Read More  Python: A History in Tandem

File modes

Many languages specify a “mode” when opening files. Modes vary, but this is common notation:

  • w to write
  • r to read
  • r+ to read and write
  • a to append only

Some languages, such as Java and Groovy, let you determine the mode based on which class you use to load the file.

Whichever way your programming language determines a file’s mode, it’s up to you to ensure that you’re appending data—unless you intend to overwrite a file with new data. Programming languages don’t have built-in prompts to warn you against data loss, the way file choosers do.

 

New language and old tricks

Every programming language has a unique way of accomplishing a task; that’s why there are so many languages to choose from. You can and should choose the language that works best for you. But once you understand the basic constructs of programming, you can also feel free to try out different languages, without fear of not knowing how to accomplish basic tasks. More often than not, the pathways to a goal are similar, so they’re easy to learn as long as you keep the basic concepts in mind.

 

This article is republished in opensource.com


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

Ackley Wyndam

Related Topics
  • BigData
  • C++
  • Coding
  • Groovy
  • Java
  • Lua
  • Programming
  • programming languages
  • Python
  • Writing Code
You May Also Like
Getting things done makes her feel amazing
View Post
  • Computing
  • Data
  • Featured
  • Learning
  • Tech
  • Technology

Nurturing Minds in the Digital Revolution

  • April 25, 2025
View Post
  • Software
  • Technology

Canonical Releases Ubuntu 25.04 Plucky Puffin

  • April 17, 2025
View Post
  • Software
  • Technology

IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management

  • March 27, 2025
View Post
  • Data
  • Engineering

Hiding in Plain Site: Attackers Sneaking Malware into Images on Websites

  • January 16, 2025
Vehicle manufacturing
View Post
  • Software

IBM Study: Vehicles Believed to be Software Defined and AI Powered by 2035

  • December 12, 2024
IBM and Ferrari Premium Partner
View Post
  • Data
  • Engineering

IBM Selected as Official Fan Engagement and Data Analytics Partner for Scuderia Ferrari HP

  • November 7, 2024
dotlah-smartnation-singapore-lawrence-wong
View Post
  • Data
  • Enterprise
  • Technology

Growth, community and trust the ‘building blocks’ as Singapore refreshes Smart Nation strategies: PM Wong

  • October 8, 2024
nobel-prize-popular-physics-prize-2024-figure1
View Post
  • Data
  • Featured
  • Technology

They Used Physics To Find Patterns In Information

  • October 8, 2024

Stay Connected!
LATEST
  • college-of-cardinals-2025 1
    The Definitive Who’s Who of the 2025 Papal Conclave
    • May 7, 2025
  • conclave-poster-black-smoke 2
    The World Is Revalidating Itself
    • May 6, 2025
  • 3
    Conclave: How A New Pope Is Chosen
    • April 25, 2025
  • Getting things done makes her feel amazing 4
    Nurturing Minds in the Digital Revolution
    • April 25, 2025
  • 5
    AI is automating our jobs – but values need to change if we are to be liberated by it
    • April 17, 2025
  • 6
    Canonical Releases Ubuntu 25.04 Plucky Puffin
    • April 17, 2025
  • 7
    United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services
    • April 15, 2025
  • 8
    Tokyo Electron and IBM Renew Collaboration for Advanced Semiconductor Technology
    • April 2, 2025
  • 9
    IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management
    • March 27, 2025
  • 10
    Tariffs, Trump, and Other Things That Start With T – They’re Not The Problem, It’s How We Use Them
    • March 25, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    IBM contributes key open-source projects to Linux Foundation to advance AI community participation
    • March 22, 2025
  • 2
    Co-op mode: New partners driving the future of gaming with AI
    • March 22, 2025
  • 3
    Mitsubishi Motors Canada Launches AI-Powered “Intelligent Companion” to Transform the 2025 Outlander Buying Experience
    • March 10, 2025
  • PiPiPi 4
    The Unexpected Pi-Fect Deals This March 14
    • March 13, 2025
  • Nintendo Switch Deals on Amazon 5
    10 Physical Nintendo Switch Game Deals on MAR10 Day!
    • March 9, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.