reading from a file using a function
Dec 9, 2012 at 6:41am UTC
Hello everyone!
I have a school project Im having issues with, well just one part rather. Here is my code im trying to implement as a function that reads a company address from a file: (this code is functional:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char STR30[30]; // programmer defined data type
typedef STR30 STR30Address[3]; // another pddt ...
using namespace std;
int main(void )
{
STR30Address info;
FILE * checkInFile;
int i;
checkInFile = fopen("./CompanyInfo.dat" ,"rt" );
if (checkInFile == NULL)
{
printf(" Can't open check descriptions file ...\n" );
while (getchar() != '\n' );
exit(-300); // reqs <stdlib.h>
}
for (i=0; i < 3; i++)
{
fgets(info[i],80,checkInFile); //read max 80 bytes from current rec.
info[i][strlen(info[i])-1] = 0; // replace /n with /o terminator
}
fclose(checkInFile);
for (i=0; i < 3; i++)
printf(" %-30s\n" ,info[i]);
fflush(stdin),getchar();
return 0;
}
And this is my attempt at the function with the variable info[3][30] passed by reference (not working right):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char STR30[30]; // programmer defined data type
typedef STR30 STR30Address[3]; // another pddt ...
using namespace std;
void getCompanyInfo(STR30Address *info);
int main(void )
{
STR30Address info;;
getCompanyInfo(&info);
for (int i=0; i < 3; i++)
printf(" %-30s\n" ,info[i]);
fflush(stdin),getchar();
return 0;
}
void getCompanyInfo(STR30Address *info)
{
FILE * checkInFile;
int i; //loop counter
checkInFile = fopen("./CompanyInfo.dat" ,"rt" );
if (checkInFile == NULL)
{
printf(" Can't open check descriptions file ...\n" );
while (getchar() != '\n' );
exit(-300); // reqs <stdlib.h>
}
for (i=0; i < 3; i++)
{
fgets(*info[i],35,checkInFile); //read max 35 bytes from current rec.
*info[i][strlen(*info[i])-1] = 0; // replace /n with /o terminator
}
fclose(checkInFile);
}
Its giving me this output:
1 2 3 4 5 6
Sabre Corporation
Uҋ
?I?Ȉ
Segmentation fault (core dumped)
It should be a 3 line address.
Any Help would be greatly appreciated!
Dec 11, 2012 at 3:17pm UTC
Won't run for me, seems to die here: for (i=0; i < 3; i++)
Dec 11, 2012 at 5:01pm UTC
info is not an array, so you should stop treating it like it is one. (And this is not passing by reference -- passing by reference would use a... reference. This is passing a pointer by value.)
*info[i]
is equivalent to *(info[i])
and what you need for this to work is: (*info)[i]
Topic archived. No new replies allowed.