Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can I read from a text file?

+19 votes
asked Oct 16, 2018 by anonymous
Hello everyone

Can I open a text file in this online IDE and read from it and output the output to another text file?

Thanks!

4 Answers

0 votes
answered Jul 31, 2019 by Matthew Murrill (150 points)

Reading to or from a text file is possible. In C++, it can be done with ifstream/ofstream: http://www.cplusplus.com/doc/tutorial/files/ 

However, it depends on the language and IDE you are using. If the IDE allows you to import txt files to read from, then you should be able to pull info. from them.

commented Aug 1, 2019 by kuelf
This doesn't answer the question.
+4 votes
answered Sep 1, 2019 by NavarroAndorid (360 points)
In order to read a file from a program you need to include it in the same project.  For example, you can have the data in data.txt and your code in myCode.  You can add additional files to your project using Ctrl + M.  When you list your projects, you will only be able to see the projects names but not the file they contain.  If you want to do so, you can download the project to your computer and unzip it.
0 votes
answered Sep 3, 2019 by anonymous
Open file to read and another to write to. Read from first file and write contents into second file. Close the file.

Default path is file where scripts are held/where compiled from

FILE *ptr, *ptr1;

ptr = fopen("file name/path", "mode");

ptr1 = fopen("file name/path", "mode");

open and write to file etc

fclose("ptr"); //closes and saves file

fclose("ptr1"); //closes and saves file
commented Mar 12, 2020 by Matthew Dickey (100 points)
What is the path used on this website?
0 votes
answered Apr 8, 2022 by userdotexe (1,340 points)

Yes. I did this for you in python at https://onlinegdb.com/Cp84508o9:

File system:

.

  \ main.py

  \ YOUR_FILE

  \ OTHER_FILE

(Example) Your file's content:

A text file I uploaded to Online GDB.
Hello, World!

Main.py's content:

Finput = open('YOUR_FILE','r').read()
F = open('OTHER_FILE','a')
F.write(Finput)
F.close()
print(open('OTHER_FILE','r').read())

Output:

A text file I uploaded to Online GDB.
Hello, World!

:)

commented Apr 8, 2022 by userdotexe (1,340 points)
You can use the actual project link to see how to do it.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...