Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Simple C program file input/output int main(int argc , char*argv[]): char*argv[]

ID: 3846701 • Letter: S

Question

Simple C program file input/output

int main(int argc , char*argv[]):char*argv[] contains the input file name if the file name is not provided then display the error message. If unable to open the file (in case of wrong file name) then also display (different) error message.

Here are some hints for error handling

If argc value is not equal to 2 that means file name is not provided by the user.

If file pointer has a value NULL (after fopen call) that means file could not be opened successfully.

int read_info(char *, int *): This function takes a file name to read the input from and an integer array to store the input from the file. It returns the size of the input which is the basically the number at the first line of the input file (see below).This function opens the input text file if unable to open return -1 or any negative indicating unable to open the file that can be used in the main to display the error message. If able to open the input file successfully then return the size of the input.

Sample input file

5

112

335

421

611

220

Here 5 is the size of the input. Read this number first (using fscanf function). Then use it to run a loop to read the input from the file and store them in the integer array.

Again there are multiple ways to read input from a file above suggestion is just one way. You are free to read input from the file using any other function /method.

void printArray(int *, int ) -This function prints the content of the integer array. It takes an integer array and the size of the input.

Note

Implement the pre-lab using the function prototype as given in the document. They are sufficient and should not be modified for the pre-lab.

Don’t use any global variable in the implementation.

Explanation / Answer

#include <stdio.h>

int read_info(char* argv[],int* arr)
{
FILE *file = fopen(argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
return -1;
else
{ int num,i,a;
fscanf(file,"%d", &num);
for(i=0;i<num;i++)
{
fscanf(file,"%d", &a);
arr[i]=a;
}
return num;
}
}
void printArray(int *arr, int size)
{
int i=0;
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
}
int main(int argc , char*argv[])
{
int arr[100005]={0};
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename ", argv[0] );
}
else
{
int num=0;
if((num=read_info(argv,arr))==-1)
{
printf( "Could not open file " );
}
else
{
printf( "There are %d elements in the file ", num);
printArray(arr,num);
}
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote