I am trying to read the first value of a file, allocate an array of the amount equal to the first value, then read the rest (the number of places already defined) of the file into that array. I have already done something similar using file pointers:
Code:
int main(int argc, char *argv[])
{
int numberOfChar;
int thisInt;
int currentInt;
FILE *fp;
fp=fopen("test.txt", "rb");
if (fscanf(fp, "%d", &numberOfChar) == 1)
printf("%d\n", numberOfChar);
for(currentInt = 0; currentInt < numberOfChar; currentInt++)
{
fscanf(fp, "%d", &thisInt);
printf("%d\n", thisInt);
}
printf("\n");
printf("\n");
return 0;
}
But I'm trying to do it with arrays now, so as to manipulate the array afterward. I can read the first int of the file and allocate the array:
Code:
int numberOfChar;
FILE *fp;
fp=fopen("test.txt", "rb");
if (fscanf(fp, "%d", &numberOfChar) == 1)
int x[numberOfChar]; //making array x have a size of numberOfChar
But reading the rest of the file, only to the numberOfChar, I can't figure out. I have seen arrays being made in C++ from user input:
Code:
int s;
for (s = 0; s < numberOfChar; s++)
{
cout << "Enter an integer: ";
cin >> A[s];
}
for (s = 0; s < numberOfChar; s++)
cout << A[s] << endl;
But I am trying to do it from a file, in C. I believe it will be a similar for loop though. I believe I have it allocated right, but how do I keep writing data into the array? Thank you in advance!