0% found this document useful (0 votes)
9 views

Memoryfilehandling

The document discusses dynamic memory allocation using malloc() and free() and creating programs to read from and write to files. It includes code samples to allocate memory for an array using malloc, write user input to a file, and read the file contents. The code demonstrates basic file handling and dynamic memory allocation in C.

Uploaded by

rajeshwarade644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Memoryfilehandling

The document discusses dynamic memory allocation using malloc() and free() and creating programs to read from and write to files. It includes code samples to allocate memory for an array using malloc, write user input to a file, and read the file contents. The code demonstrates basic file handling and dynamic memory allocation in C.

Uploaded by

rajeshwarade644
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

AIM: Memory and file handling

1.Explore the concept of dynamic memory allocation using malloc() and


free().
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
for (i=0;i<n;++i)
{
ptr[i]=i+1;
}
printf("The elements of the array are: ");
printf("[");
for (i=0;i<n-1;++i)
{
printf("%d, ",ptr[i]);
}
for (i=n-1;i<n;++i)
{
printf("%d]",ptr[i]);
}

}
return 0;
}

Output:
2. Create programs to read from and write to files.
Code:
#include <stdio.h>
int main()
{
FILE *file;
char userInput[100];
printf("Enter some text: ");
fgets(userInput, sizeof(userInput), stdin);
file = fopen("user_input.txt", "w");
if (file == NULL)
{
printf("Could not open the file for writing.\n");
return 1;
}
fprintf(file, "File have:- %s", userInput);
fclose(file);
printf("User input written to the file successfully.\n");
char content[100];
file = fopen("user_input.txt", "r");
if (file == NULL)
{
printf("Could not open the file for reading.\n");
return 1;
}
while (fgets(content,sizeof(content),file) != NULL) //for reading whats in
file...
{
printf("%s", content);
}
fclose(file);
return 0;
}

Output:

You might also like