I have a program that reads integers from an external data file. I'm
trying to figure out how to get the result in
reverse order. For eg., if file contains 1,2,3,4 then I'd like to get
the output 4,3,2,1. Thanks in advance.
Wan
int main()
{
FILE *f;
int c[20];
f=fopen("C:\File.text","r");
if (!f)
return 1;
while (f!=NULL)
{
printf("%s",c);
}
fclose(f);
return 0;
}
size_t count = <length of file> / sizeof(int);
while(count--)
printf("%d",c[count]);
Is that what you need?
Alex
Are you sure you have one? The code you show below is not it.
> I'm trying to figure out how to get the result in
> reverse order. For eg., if file contains 1,2,3,4 then I'd like to get
> the output 4,3,2,1.
Sounds like homework to me. On the off chance it's not, what practical problem are you trying to solve?
> int main()
> {
>
> FILE *f;
> int c[20];
>
> f=fopen("C:\File.text","r");
Make it "C:\\File.text". Backslashes need to be escaped.
> if (!f)
> return 1;
>
> while (f!=NULL)
> {
Since the body of the loop doesn't change the value of the variable 'f', the condition will never become false. You have an infinite loop.
> printf("%s",c);
%s specifier expects a char* parameter, not an int*. Besides, 'c' was never initialized and contains random garbage.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. -- RFC 1925
>
>"Wan Andii" wrote:
>> I have a program that reads integers from an external data file.
>> I'm trying to figure out how to get the result in reverse order.
>> For eg., if file contains 1,2,3,4 then I'd like to get the
>> output 4,3,2,1.
>>
>> int main()
>>
>> {
>>
>> FILE *f;
>> int c[20];
>>
>> f=fopen("C:\File.text","r");
>>
>> if (!f)
>> return 1;
>>
>
>size_t count = <length of file> / sizeof(int);
Does sizeof(int) have anything to do with their text representation in
the file? For the given sample on a 32 bit system, this evaluates to
1 which seems to be short by 3.
>
>while(count--)
> printf("%d",c[count]);
>
>
>Is that what you need?
>
>Alex
--
Remove del for email
Good catch. I was thinking about binary files with integers for
some reason.
Alex