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  Backup & Disaster Recovery Strategies For BigQuery

 

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  Our I/O 2022 Announcements: In Demo Form

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  The Eclipse Foundation Launches The Sparkplug Working Group To Bring Device Communications Standardization To The Industrial Internet Of Things And Industrial Automation

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
View Post
  • Data
  • Multi-Cloud
  • Platforms

Microsoft And Oracle Expand Partnership To Deliver Oracle Database Services On Oracle Cloud Infrastructure In Microsoft Azure

  • September 14, 2023
View Post
  • Data
  • Learning

Resources to Take Your Charts From Bland to Beautiful

  • September 6, 2023
View Post
  • Software
  • Technology

Series Of Events Will Highlight Generative AI Use Cases Powered By Open Source Software

  • September 6, 2023
View Post
  • Data
  • Platforms
  • Technology

Reimagine Data Analytics For The Era Of AI

  • August 30, 2023
View Post
  • Data
  • Platforms

IBM Introduces ‘Watsonx Your Business’

  • August 28, 2023
View Post
  • Data
  • Research
  • Technology

Using Machine Learning To Help ZSL & Network Rail Monitor And Improve Biodiversity Near British Railways

  • August 20, 2023
Internet of Things
View Post
  • Software
  • Technology

OpenHW Group Announces Tape Out of RISC-V-Based CORE-V MCU Development Kit for IoT Built with Open-Source Hardware & Software

  • August 16, 2023
Redis logo
View Post
  • Data
  • Platforms
  • Software Engineering

Redis 7.2 Sets New Standard For Developers To Harness The Power Of Real-Time Data

  • August 15, 2023

Stay Connected!
LATEST
  • 1
    Nvidia H100 Tensor Core GPUs Come To Oracle Cloud
    • September 24, 2023
  • 2
    Combining AI With A Trusted Data Approach On IBM Power To Fuel Business Outcomes
    • September 21, 2023
  • 3
    Start Your Ubuntu Confidential VM With Intel® TDX On Google Cloud
    • September 20, 2023
  • Microsoft and Adobe 4
    Microsoft And Adobe Partner To Deliver Cost Savings And Business Benefits
    • September 20, 2023
  • Coffee | Laptop | Notebook | Work 5
    First HP Work Relationship Index Shows Majority of People Worldwide Have an Unhealthy Relationship with Work
    • September 20, 2023
  • 6
    Oracle Expands Distributed Cloud Offerings to Help Organizations Innovate Anywhere
    • September 20, 2023
  • 7
    Huawei Connect 2023: Accelerating Intelligence For Shared Success
    • September 20, 2023
  • 8
    Huawei Releases Data Center 2030, Leading Innovation and Development of New Data Centers
    • September 20, 2023
  • Penguin 9
    How To Find And Fix Broken Packages On Linux
    • September 19, 2023
  • Volkswagen 10
    Volkswagen Races Toward Next-Gen Automotive Manufacturing Leadership With Google Cloud And T-Systems
    • September 19, 2023
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
    VMware Scales Multi-Cloud Security With Workforce Identity Federation
    • September 18, 2023
  • Intel Innovation 2
    Intel Innovation 2023
    • September 15, 2023
  • 3
    Microsoft And Oracle Expand Partnership To Deliver Oracle Database Services On Oracle Cloud Infrastructure In Microsoft Azure
    • September 14, 2023
  • 4
    Real-Time Ubuntu Is Now Available In AWS Marketplace
    • September 12, 2023
  • 5
    IBM Brings Watsonx To ESPN Fantasy Football With New Waiver Grades And Trade Grades
    • September 13, 2023
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.