简体   繁体   English

C 将数组元素打印到终端和 txt 文件的程序

[英]C program to print array elements to terminal and txt file

The API's that I am supposed to to use for this are open(), write() and sprintf().我应该为此使用的 API 是 open()、write() 和 sprintf()。 If you are going to post a response of answer please don't recommend any other API's.如果您要发布对答案的回应,请不要推荐任何其他 API。

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.我的程序应该扫描 10 个元素,然后以相反的顺序将这些元素打印到终端和一个 txt 文件。

#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().我知道如何使用 fprintf() 并使用 API 写入文本文件,但现在我的说明是使用 open() 和 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.我的问题是我该怎么做才能解决这个问题并在 txt 文件中获得正确的 output。 Thanks.谢谢。

I tried the above code.我试过上面的代码。

In this for loop在这个for循环中

    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 .数组arr的每个元素都被写入buffer的开头,覆盖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 .在这种情况下,数组的每个下一个元素都将附加到已存储在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程序 output 是

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.在for循环里面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM