File reading & writing
Initiate coding adventures with ease - set up new projects effortlessly
File reading and writing is useful if you want your programs to store information or access external data. Here’s how you can create, save, and edit files in your JDoodle projects. We distinguish between project files, where your code is stored, and input/output files, where your program reads and writes to. These are stored in different locations. This document primarily deals with input/output files.
Prerequisites
- A JDoodle Account
- Basic knowledge of programming file handling
Where your files are stored in JDoodle
Path | Description |
---|---|
/myfiles | |
Doodle program. /uploads | |
Doodle interface. / | In the advanced IDE, the directory where your project files are stored. See the Advanced IDE documentation for how to upload project files. |
How to upload input files
- You can upload files from your computer to JDoodle to the /uploads folder.
- Open the Input Files tab on the right hand sidebar of the IDE (or the bottom, if you have moved them)
- Drag your file(s) or click the browse button to upload them
- Your files will be available in the /uploads folder
- Input files are not editable: any changes your program makes to a file in /uploads will not be saved
How to download output files
Once you have written to or modified a file in JDoodle, you can check or access its contents as follows:
- Open the Input/Output tab on the right hand sidebar of the IDE (or the bottom, if you have moved them)
- Click “Generated Files” to see a list of generated files and download these
Example code for file operations in JDoodle
Writing to a File in /myfiles
This C code writes text to a file in the /myfiles directory.
#include <stdio.h>
void writeFile() {
FILE *file;
// Open a file in write mode in the /myfiles directory
file = fopen("/myfiles/example.txt", "w");
if (file == NULL) {
printf("Error opening file in /myfiles.\n");
return;
}
// Write to the file
fprintf(file, "Hello, JDoodle in /myfiles!\n");
fclose(file);
printf("File written successfully to /myfiles.\n");
}
Reading a File from /uploads
Assuming you’ve uploaded a file called input.txt to the /uploads directory, this C code reads and prints its contents.
#include <stdio.h>
void readFile() {
FILE *file;
char buffer[256];
// Open the uploaded file in read mode
file = fopen("/uploads/input.txt", "r");
if (file == NULL) {
printf("Error opening file in /uploads.\n");
return;
}
// Read and print the file contents
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
printf("File read successfully from /uploads.\n");
}
Main Function
Combine the above functions in a main function to execute them:
int main() {
writeFile();
readFile();
return 0;
}
Support and resources
Is your issue still not resolved? Here are a few things you can do:
- Contact us by filling out this form.
- Read FAQs on JDoodle’s IDE.
- Drop your question in our JDoodle community.