This repository has been archived on 2023-10-26. You can view files and clone it, but cannot push or open issues or pull requests.
VSMechatronics/Exercises/C18/ex3.c

61 lines
1.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
// Main () - execution starts here
int main (void)
{
// Declate file stream variables
FILE *fInput, *fOutput;
// 8x the maximum filename length on most filesystems should be a decent size
char filename[2049] = { 0 };
printf("Enter filename: ");
scanf("%2048s", filename);
// Other variables needed
int i, d, d2;
// Try and open the text "sample.txt" (in the current directory) file for writing
fOutput = fopen (filename, "w");
// Check we were able to open the file
if ( fOutput == NULL)
{
printf ("The file could not be opened for writing, exiting\n");
return -1;
}
// Use a loop to write values to the newly created file
for ( i = 1 ; i <= 10 ; i++)
{
fprintf (fOutput, "%d %d\n", i, i*i);
}
// And close the file
fclose (fOutput);
// Try and open the binary "numbers " (in the current directory) file for reading
fInput = fopen ("numbers.txt", "r");
// Check we were able to open the file
if ( fInput == NULL)
{
printf ("The file could not be opened for reading, exiting\n");
return -1;
}
// Read, line by line the 10 values written into variable d
// and then display the contents of d on the screen
for ( i = 1 ; i <= 10 ; i++)
{
fscanf (fInput, "%d %d", &d, &d2);
printf ("Value read from file: %d %d\n", d, d2);
}
// And close the file
fclose (fInput);
return (0); // Exit indicating success
}