Reputation: 19
The API's that I am supposed to to use for this are open(), write() and sprintf(). If you are going to post a response of answer please don't recommend any other API's.
My program is supposed to scan for 10 elements and then print the elements in reverse order to the terminal and to a txt file.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <err.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd;
char buffer[100];
int *arr;
int i;
arr = malloc(10 * sizeof(int));
fd = open("file.txt", O_WRONLY | O_CREAT, 0644);
if (fd < 0)
{
perror("write() failed\n");
exit(-1);
}
printf("Input 10 elements in the array:\n");
for(int i = 0; i < 10; i++){
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
sprintf(buffer, "Elements in array are: ");
// write(fd, buffer,strlen(buffer));
for(int j=9; j>=0; j--){
//print to console
printf("\n%d ", arr[j]);
sprintf(buffer,"\n%d", arr[i]);
}
//write to file
write(fd, buffer,strlen(buffer));
close(fd);
free(arr);
printf("\n");
return 0;
}
The elements of the array print in reverse order to the terminal perfectly fine. The area I am stuck on is printing it to a text file. I know how to use fprintf() and writing to a text file with that API but right now my instructions are to use open() and write(). In my text file I have the following:
1
My question is what can I do to fix this and get the correct output in the txt file. Thanks.
I tried the above code.
Upvotes: 1
Views: 118
Reputation: 311038
In this for loop
for(int j=9; j>=0; j--){
//print to console
printf("\n%d ", arr[j]);
sprintf(buffer,"\n%d", arr[i]);
}
each element of the array arr
is being written in the beginning of buffer
overwriting the previous content of buffer
.
Instead you could write for example
int offset = 0;
for(int j=9; j>=0; j--){
//print to console
printf("\n%d ", arr[j]);
offset += sprintf(buffer + offset,"\n%d", arr[i]);
}
In this case each next element of the array will be appended to the string already stored in buffer
.
Here is a demonstration program.
#include <stdio.h>
int main( void )
{
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( arr ) / sizeof( *arr );
char buffer[100];
int offset = 0;
for (size_t i = N; i != 0; )
{
offset += sprintf( buffer + offset, "\n%d", arr[--i] );
}
puts( buffer );
}
The program output is
9
8
7
6
5
4
3
2
1
0
Another approach is to move this statement
write(fd, buffer,strlen(buffer));
inside the for loop.
Upvotes: 2