简体   繁体   English

将用 read() 读取的数据写入 C 中的 int 数组

[英]Writing data read with read () to int array in C

I have a file with numbers on each line.我有一个每行都有数字的文件。 I am trying to write the data read from the file to the int array with the read () function.我正在尝试使用 read() function 将从文件中读取的数据写入 int 数组。 I can read the file and print it to the terminal.我可以读取文件并将其打印到终端。 How can i get the numbers i read into arr array?我怎样才能得到我读入 arr 数组的数字?

Here is my code这是我的代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

int main() {
    int len, fd,arr[10000],i=0;
    fd = open("1.txt", O_RDONLY);
    if (fd >= 0) {

        while(read(fd, &len, sizeof(int)) > 0){
            write(1, &len, sizeof(int));

        }
    }

    close(fd);

    return 0;
}

On most (all?) implementations, a integer stores the binary representation of a number in the bits and bytes of that integer.在大多数(全部?)实现中,integer 将数字的二进制表示存储在 integer 的位和字节中。 In the other hand, a string and something like your text file uses bytes to store the ASCII value of digits, spaces and line feeds.另一方面,字符串和文本文件之类的内容使用字节来存储数字、空格和换行符的 ASCII 值。

int (assuming 4 byte with 8 bit each, big endian) may store the value 1234 this way: int (假设 4 字节,每个字节 8 位,大端)可以这样存储值 1234:

Address   0x42  0x43  0x44  0x45
Value     0x00  0x00  0x04  0xD2
Text       NUL   NUL   EOT    Ò

In the other hand, a string can contain the ASCII values of each character that represents a text.另一方面,字符串可以包含代表文本的每个字符的 ASCII 值。 The String "1234" could be stored like this:字符串“1234”可以这样存储:

Address   0x82  0x83  0x84  0x85  0x86
Value     0x31  0x32  0x33  0x34  0x00
Text        1     2     3     4    NUL

When you do a read, you read the characters of the text file.当您进行读取时,您会读取文本文件的字符。 Reading them into a char array is easy, you do not need to do any conversation, only add the NUL-Byte at the end.将它们读入char数组很容易,您无需进行任何对话,只需在末尾添加 NUL-Byte。 When you want to get the number, you have to convert them from a string.当您想获取数字时,您必须将它们从字符串转换。

This means you have to read the file, you can do this with read() if you want, and store the content in a char array, add a NUL-Byte and then convert the resulting string with a function like strtol() or sscanf() .这意味着您必须读取文件,如果需要,您可以使用read()执行此操作,并将内容存储在char数组中,添加 NUL 字节,然后使用 function 转换结果字符串,如strtol()sscanf()

What you are doing你在做什么

What you do is reading the ASCII characters into the int len .您所做的是将 ASCII 字符读入int len When you use a debugger before the write() call, you can check the value of len .write()调用之前使用调试器时,可以检查len的值。 In my case i used this as an input file:就我而言,我将其用作输入文件:

0
1
2
3
...

When i stop my debugger before write() , i see that len has the value of 170986032 == 0xA310A30 .当我在write()之前停止调试器时,我看到len的值为170986032 == 0xA310A30 My system is little endian, means the lowest byte is stored at the lowest address (unlike my previous example).我的系统是小端的,意味着最低字节存储在最低地址(与我之前的示例不同)。 Which means 0x30 comes first, then 0x0a , 0x31 and 0x0A .这意味着0x30首先出现,然后是0x0a0x310x0A From this we know that we got the following memory layout of len .由此我们知道我们得到了以下 memory 布局的len

Address Offset   0x00  0x01  0x02  0x03
Value            0x30  0x0A  0x31  0x0A
Text                0    LF     1    LF

As you can see, the text is interpreted as a int .如您所见,文本被解释为int

How to get what you want如何得到你想要的

You want to store the data into a char array.您想将数据存储到char数组中。 And then parse it.然后解析它。 I use some pseudo code to explain it better.我使用一些伪代码来更好地解释它。 This is not C-Code.这不是 C 代码。 You should learn to write your own code.您应该学习编写自己的代码。 This is just to get you an idea what you have to do:这只是为了让您了解您必须做什么:

char buffer[<buffersize>] //create a buffer array
r=read(buffer) //read the file into the buffer. You may need to repeat that multiple times to get everything
if r==error //check for errors
  <do some error handling here>
buffer[<one after the last read byte>]='\0' //add the NUL-Byte st the end, so that we have a string.
int values[<number of ints you want>]  //create an array to store the parsed values
for(<one loop for every int>) //make the loop for every int, to parse the int
  values[<index>]=strtol(buffer,&buffer,0) //parse the text to a int
  if error occured:
    <do some error handling here>

How to implement this in C is your task.如何在 C 中实现这一点是您的任务。 Keep buffer sizes in mind so you do not end with UB.请记住缓冲区大小,这样您就不会以 UB 结尾。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int fd;
    char arr[10000];
    int arr2[10000];
    ssize_t count;
    fd = open("1.txt", O_RDONLY);
    if (fd >= 0)
    {
        count = read(fd, arr, 10000); // reading from file and writing to array.
        if (count == -1)
        {
            printf("Error %d\n", errno);
            exit(0);
        }
        arr[count] = '\0';
    }

    for(int i=0; i<count; i++)  //Converting the character arrays to integer array
    {
        if(arr[i] >='0' && arr[i]<='9' )
        arr2[i] = arr[i]-'0';
        else
        {
            arr2[i] = 0; //For characters other than numbers.
        }
        
    }

    for (int i=0; i<count; i++)
    {
        printf("%d ",arr2[i]);
    }

    close(fd);

    return 0;
}

Here, I read the numbers from the file and stored into a character array, then I converted it to an integer array.在这里,我从文件中读取数字并存储到字符数组中,然后将其转换为 integer 数组。 If there is any character other than number, I am assigining it as zero here in the array.如果有数字以外的任何字符,我在数组中将其分配为零。

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

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