You are on page 1of 5

Roll No.

and name: 20bcl086- jaydtt patel


Course code and name: 2CS101 Computer programming
Practical no: 10

Practical No.:10(a)

AIM: To calculate the length of a file

Methodology followed:

#include <stdio.h>

long int findSize(char file_name[])


{
// opening the file in read mode
FILE* fp = fopen(file_name, "r");

// checking if the file exist or not


if (fp == NULL) {
printf("File Not Found!\n");
return -1;
}

fseek(fp, 0L, SEEK_END);

// calculating the size of the file


long int res = ftell(fp);

// closing the file


fclose(fp);

return res;
}

// Driver code
int main()
{
char file_name[] = { "a.txt" };
long int res = findSize(file_name);
if (res != -1)
printf("Size of the file is %ld bytes \n", res);
return 0;
}
Theoretical Principles used: Here we extensively used the concept of file
management with a little use of if..else.
Input/Output:

Practical No.: 10(b)

AIM: To concatenate two files

Methodology followed:

#include <stdio.h>
#include <stdlib.h>

int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result


FILE *fp3 = fopen("file3.txt", "w");
char c;

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)


{
puts("Could not open files");
exit(0);
}

// Copy contents of first file to file3.txt


while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);

// Copy contents of second file to file3.txt


while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");

fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

Theoretical Principles used: Here we used the concept of file management


and the function putc().

Input/Output:

Practical No.: 10C(c)

AIM: To copy content of one file in to another file

Methodology followed:

#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading: \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing: \n");
scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}

Theoretical Principles used: Here we used the concept of file


management and the function close().

Input/Output:
Conclusion:

In this whole practical I learn about how calculate length of file and how to To
concatenate two files.

You might also like