I/O from a file

I need to give inputs for my code from a file which is on my local storage and want the the output in another file which should be in my local storage.
How do I do this guys?? Need help!!

2 Likes

Every language has predefined methods for handling file I/O.

Considering for C language, the most basic of all:

C handles File handling through pointers.A pointer is allocated for storing address of file. This is a special pointer of FILE type. A FILE is a macro. You can use methods like fscanf(),fprintf(),fread(),fwrite(),fgetc(),fputc() and many more. You may visit this link for more details.
Here is a code snippet for taking input from a file and writing output to a file:

Input from a file:

#include <stdio.h>
int main()
{
   int num;
   FILE *fptr;

   if ((fptr = fopen("C:\\program.txt","r")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   fscanf(fptr,"%d",&num);

   printf("Value of n=%d",num);
   fclose(fptr); 
  
   return 0;
}

Output to a file:

 #include <stdio.h>
int main()
{
   int num;
   FILE *fptr;
   fptr = fopen("C:\\program.txt","w");

   if(fptr == NULL)
   {
      printf("Error!");   
      exit(1);             
   }

   printf("Enter num: ");
   scanf("%d",&num);

   fprintf(fptr,"%d",num);
   fclose(fptr);

   return 0;
}  

Remember that you would have to consider the mode for opening a file. See here for more details.
Also, while entering the location of file in fopen(), enter the complete path of the file, along with the filename.extension.

Source for the code and description for file handling

Hello there.
If you like to use python 3, here is a template that I made in order to handle I/O issues first line checks and stuff. You can use it as a whole or to take the part you are interested to, (the I/O in this case).
Best Regards.
Robert.

import sys

itIsTheFirstLine = True     #This variable is about the input line. If the line is the first the variable itIsTheFirstLine is True.
T=0     #The number of lines with usefull Data. the number of tierations.
result = "Not any result right now" #this is used for the result wich is printed in the end of the code with the default value.
testSum = 0 #This is used to make the mainCheckFunction() bit more interesting but making the function to work as add function.
countForT = 0 #this is the count vairiable that helps to check that the iterations are not more than the predefined T variable.

#the mainCheckFunction() function is doing the necessary checking before the mainCalculativFunction().
#there is always something to check
def mainCheckFunction(checkFunctionsProperty):
        if checkFunctionsProperty == True:
                return True

#The function mainCalculativFunction() solves the logical problem of the exercise.
#Now it works like a SUM function.       
def mainCalculativFunction(inputProperty):
    global testSum #This is used to make the mainCheckFunction() bit more interesting but making it to work as add function.
    if mainCheckFunction(True):
        testSum = int(inputProperty) + testSum
        return str(testSum) 


#The function firstLineCorrection() changes the itIsTheFirstLine to False and stores the N to the variable T
def firstLineCorrection(inputForNInitiation):
    global itIsTheFirstLine
    global T
    itIsTheFirstLine = False
    T = inputForNInitiation
    
#this is the function that uses the countForT to check up that the iterations are not more than what the T variable defines    
def iterationsCheck(hereGoesTheCountForTParameter):
    if hereGoesTheCountForTParameter >= int(T):
        return True

#My first thought was to use "for in" loop but after using it I figured out that the use of Range is the best solution.
#As I know, a loop with range is more efficient than the typical "for in" loop.
#Use this function in case of sorting, or in the case of temparated array. you will not regret it.    
def printFromArray(Arrayname, probablytheTVariable):
    for i in range(int(probablytheTVariable)):
        print(str(Arrayname[i]))


#The main iteration, (AKA the main loop), now is the main() function. 
#The separation of code to functions blocks keeps the template simple and clear.    
def main():
    global countForT
    for N in sys.stdin:
        print("itIsTheFirstLine now is " + str(itIsTheFirstLine))
        if itIsTheFirstLine == True:
            firstLineCorrection(N)
        else:
            result = mainCalculativFunction(N)
            countForT += 1
            print("the T which represent the number of lines with input data, now is " + str(T))        
            if iterationsCheck(countForT):
                #here add code when the answer comes in the end as a final result.
                print("the result of the main calculative fuction know as mainCalculativFunction() now is " + result)
            else:
                #Here add code if there are many answers that are coming separately with every iteration.
                print ("the N now which is the value of the last input now is " + str(N))
                
if __name__ == "__main__": main()

Where is the code of asking input from external file? Can you explain your full code that how it is taking input from external file?

Nice question! I also have a doubt that how to take input in Python from external file and print it to the external file. It would be helpful for getting input the test cases from external file in Competitive programming-

Hello again!
I was asked for a template that works with external files.
So here is the External files version of my code:

itIsTheFirstLine = True     #This variable is about the input line. If the line is the first the variable itIsTheFirstLine is True.
T=0     #The number of lines with usefull Data. the number of tierations.
result = "Not any result right now" #this is used for the result wich is printed in the end of the code with the default value.
testSum = 0 #This is used to make the mainCheckFunction() bit more interesting but making the function to work as add function.
countForT = 0 #this is the count vairiable that helps to check that the iterations are not more than the predefined T variable.
fileForOutput = open('output.txt','w')
fileForInput = open('input.in','r')


#the mainCheckFunction() function is doing the necessary checking before the mainCalculativFunction().
#there is always something to check
def mainCheckFunction(checkFunctionsProperty):
        if checkFunctionsProperty == True:
                return True

#The function mainCalculativFunction() solves the logical problem of the exercise.
#Now it works like a SUM function.       
def mainCalculativFunction(inputProperty):
    global testSum #This is used to make the mainCheckFunction() bit more interesting but making it to work as add function.
    if mainCheckFunction(True):
        testSum = int(inputProperty) + testSum
        return str(testSum) 

#The function firstLineCorrection() changes the itIsTheFirstLine to False and stores the N to the variable T
def firstLineCorrection(inputForNInitiation):
    global itIsTheFirstLine
    global T
    itIsTheFirstLine = False
    T = inputForNInitiation
    
#this is the function that uses the countForT to check up that the iterations are not more than what the T variable defines    
def iterationsCheck(hereGoesTheCountForTParameter):
    if hereGoesTheCountForTParameter >= int(T):
        return True
    
#My first thought was to use "for in" loop but after using it I figured out that the use of Range is the best solution.
#As I know, a loop with range is more efficient than the typical "for in" loop.
#Use this function in case of sorting, or in the case of temparated array. you will not regret it.    
def printFromArray(Arrayname, probablytheTVariable):
    for i in range(int(probablytheTVariable)):
        print(str(Arrayname[i]))

    
#The main iteration, (AKA the main loop), now is the main() function. 
#The separation of code to functions blocks keeps the template simple and clear.    
def main():
    global countForT
    for N in fileForInput:
        print("itIsTheFirstLine now is " + str(itIsTheFirstLine))
        fileForOutput.write("itIsTheFirstLine now is " + str(itIsTheFirstLine))
        #print("itIsTheFirstLine now is " + str(itIsTheFirstLine) end='\n' file=f)
        if itIsTheFirstLine == True:
            firstLineCorrection(N)
        else:
            result = mainCalculativFunction(N)
            countForT += 1
            print("the T which represent the number of lines with input data, now is " + str(T)) 
            fileForOutput.write("the T which represent the number of lines with input data, now is " + str(T))       
            if iterationsCheck(countForT):
                #here add code when the answer comes in the end as a final result.
                print("the result of the main calculative fuction know as mainCalculativFunction() now is " + result)
                fileForOutput.write("the result of the main calculative fuction know as mainCalculativFunction() now is " + result)
            else:
                #Here add code if there are many answers that are coming separately with every iteration.
                #here is the best location for the printFromArray()function.
                print ("the N now which is the value of the last input now is " + str(N))
                fileForOutput.write("the N now which is the value of the last input now is " + str(N))
                
if __name__ == "__main__": main()



#Optimal print example
#print("Case #", str(unregisteredcase), ": ", number_string2, " ",sep="", end='\n', file=f)


fileForInput.close()
fileForOutput.close()
print("That's all folks!")

@bansal1232 I added an external file I/O version of my code. I hope that is what you were asking for.
Best Regards.
Robert

if you are using linux, then you can keep inputs in input.txt and run the program from command prompt as:

make filename
./filename < input.txt > output.txt

All the output will get saved to output.txt file