简体   繁体   English

如何将指针指向的textf的内容复制到char数组(即,指针-> char数组)

[英]How can i copy the contents of a textf, pointed to by a pointer, to a char array (i.e. pointer -> char array)

I am reading from a file, which, thanks to malloc, saves the content of the text file to *buffer. 我正在读取一个文件,这要感谢malloc将文本文件的内容保存到* buffer。 However, I wish to transfer the contents of file to a char array. 但是,我希望将文件的内容传输到char数组。 How can I accomplish this? 我该怎么做?

Here is my code so far: 到目前为止,这是我的代码:

#define LENGTH_OF_INPUT 49

FILE *FP = fopen("InputString.txt", "r");

char *buffer;
char InputString;

fseek(FP, 0L, SEEK_END);
s = ftell(FP);
rewind(FP);
buffer = (char*) malloc(s); /* buffer now is the content of the file */

if (buffer != NULL) /* If buffer was allocated... i.e the file exists*/
    {
    fread(buffer, s, 1, FP);
    fclose(FP); /* Must.. Close.. File.. */

    FP = NULL; /* For decaying pointer?? */

for (sizeofbuffer = 0; *buffer != '\0'; ++sizeofbuffer)
{
    *buffer++;
}

if (sizeofbuffer == LENGTH_OF_INPUT - 1 ) /* Check if the length of the string = 48 */
    {
        /* Correct length! */

        /* Also need to reset *buffer so that this for loop copies from the first letter */

        for (i = 0; *buffer != '\0' ; ++sizeofbuffer) /* Save to InputString*/
        {
            /* CODE NEEDS TO GO HERE!! */
        }
    }

I don't want to use strcpy in case the char array contains an early '\\0' 我不想在字符串数组包含早期'\\ 0'的情况下使用strcpy

EDIT: I found this http://www.cplusplus.com/forum/general/4107/ ; 编辑:我发现这个http://www.cplusplus.com/forum/general/4107/ ; don't understand it though (is it even relevant?) 虽然不了解(它甚至相关吗?)

Change this: 更改此:

buffer = (char*)malloc(s);

To this: 对此:

buffer = (char*)malloc(s+1);
buffer[s] = 0;

And return buffer after you close the file; 关闭文件后返回buffer the rest of the code is redundant. 其余代码是多余的。 In addition to that, don't forget to free the memory pointed by buffer at some later point in the execution of your program. 除此之外,别忘了在程序执行的某些时候free buffer指向的内存。


The purpose of buffer[s] = 0 is for you to be able to pass it to string functions. buffer[s] = 0的目的是使您能够将其传递给字符串函数。 A few examples: 一些例子:

printf("%s",buffer);
strcpy(buffer2,buffer);
strcat(buffer2,buffer);
if (strcmp(buffer2,buffer) == 0) ...

Even if you're not interested in that, you still need a method with which you can detect the end of the string which is stored in the memory pointed by buffer . 即使您对此不感兴趣,您仍然需要一种方法,通过该方法可以检测存储在buffer指向的内存中的字符串的结尾。 The answer above suggests the method of setting buffer[s] to a 0 (null) character. 上面的答案建议将buffer[s]设置为0(空)字符的方法。 Alternatively, you can simply use the value of s itself. 另外,您可以简单地使用s本身的值。 However, if you choose this method, then you'll have to maintain both buffer and s in a structure. 但是,如果选择此方法,则必须在结构中同时保留buffers

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

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