S
Sheldon
Hi,
I am trying to learn C from scratch and, though I do know how to
program in Python, many things in C are hard to understand - even
after reading the examples. I guess because so many variations exists.
Can someone explain why this variation of fwrite fails:
#include <stdio.h>
#include <stdlib.h>
#define ROW 15 /* In order to have more memory and no segmentation
faults, request more memory */
#define COL 15
#define FILENAME "/data/aux/test_array.dat"
double tmp[ROW][COL];
int main(void)
{
FILE *fp; /* declare a file pointer */
int i, j, data;
float count;
printf("Rows -> %d\tCol -> %d\n",ROW, COL);
/* Assigning data to the array */
count = 2.0;
for(i = 0; i < ROW; i++)
{
for(j = 0; j < COL; j++)
{
tmp[j] = count;
count++;
/* printf("%f\n",count); */
}
}
printf("Finished writing to array\n");
printf("Opening file: %s\n",FILENAME);
if ((fp = fopen(FILENAME, "wb")) == NULL)
{
fprintf(stderr, "Error opening file %s in read mode.\n",
FILENAME);
fclose(fp);
return EXIT_FAILURE;
}
else
printf("File opened successfully.\n\n");
/* Write data to file */
if(ROW*COL != fwrite(tmp, sizeof *tmp, COL, fp)) /* Checking the byte
size of the file */
{
fprintf(stderr, "Error writing to file.\n");
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
/* done writing to file */
return 0;
}
Thanks in advance!
Sheldon
I am trying to learn C from scratch and, though I do know how to
program in Python, many things in C are hard to understand - even
after reading the examples. I guess because so many variations exists.
Can someone explain why this variation of fwrite fails:
#include <stdio.h>
#include <stdlib.h>
#define ROW 15 /* In order to have more memory and no segmentation
faults, request more memory */
#define COL 15
#define FILENAME "/data/aux/test_array.dat"
double tmp[ROW][COL];
int main(void)
{
FILE *fp; /* declare a file pointer */
int i, j, data;
float count;
printf("Rows -> %d\tCol -> %d\n",ROW, COL);
/* Assigning data to the array */
count = 2.0;
for(i = 0; i < ROW; i++)
{
for(j = 0; j < COL; j++)
{
tmp[j] = count;
count++;
/* printf("%f\n",count); */
}
}
printf("Finished writing to array\n");
printf("Opening file: %s\n",FILENAME);
if ((fp = fopen(FILENAME, "wb")) == NULL)
{
fprintf(stderr, "Error opening file %s in read mode.\n",
FILENAME);
fclose(fp);
return EXIT_FAILURE;
}
else
printf("File opened successfully.\n\n");
/* Write data to file */
if(ROW*COL != fwrite(tmp, sizeof *tmp, COL, fp)) /* Checking the byte
size of the file */
{
fprintf(stderr, "Error writing to file.\n");
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
/* done writing to file */
return 0;
}
Thanks in advance!
Sheldon