programing

FILE*로 메모리 버퍼에 쓰는 방법

bestcode 2022. 9. 3. 13:21
반응형

FILE*로 메모리 버퍼에 쓰는 방법

메모리 버퍼를 FILE*로 작성하는 방법이 있습니까?TiXml에서는 xml을 FILE*로 인쇄할 수 있지만 메모리 버퍼로 인쇄할 수 없습니다.

POSIX의 메모리 사용방법이 있습니다.FILEdescriptor: 또는 원하는 의미에 따라 fmemopen과 open_memstream의 차이

C++basic_streambuf상속.

C++ 에서는, 피해야 합니다.FILE*네가 할 수 있으면.

C++ stdlib만을 사용하면 파일 또는 메모리 IO를 투과적으로 사용하는 단일 인터페이스를 만들 수 있습니다.

여기에는 표준 스트림에서 사용되는 내부 버퍼 설정(pubsetbuf)에 기재된 기술이 사용됩니다.

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>

/* This can write either to files or memory. */
void write(std::ostream& os) {
    os << "abc";
}    

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> > {
    ostreambuf(char_type* buffer, std::streamsize bufferLength) {
        this->setp(buffer, buffer + bufferLength);
    }
};

int main() {
    /* To memory, in our own externally supplied buffer. */
    {
        char c[3];
        ostreambuf<char> buf(c, sizeof(c));
        std::ostream s(&buf);
        write(s);
        assert(memcmp(c, "abc", sizeof(c)) == 0);
    }

    /* To memory, but in a hidden buffer. */
    {
        std::stringstream s;
        write(s);
        assert(s.str() == "abc");
    }

    /* To file. */
    {
        std::ofstream s("a.tmp");
        write(s);
        s.close();
    }

    /* I think this is implementation defined.
     * pusetbuf calls basic_filebuf::setbuf(). */
    {
        char c[3];
        std::ofstream s;
        s.rdbuf()->pubsetbuf(c, sizeof c);
        write(s);
        s.close();
        //assert(memcmp(c, "abc", sizeof(c)) == 0);
    }
}

유감스럽게도 교환이 불가능할 것 같습니다.FILE*그리고.fstream: std::fstream에서 FILE* 가져오기

케빈이 쓴 게 맞는 것 같아요.그러나 여기에서는 파일*.을 사용하여 실행할 수 있는 해킹이 있습니다.버퍼 크기(여기서는 100000)가 너무 작으면 버퍼가 플러시되었을 때 데이터가 손실됩니다.또한 프로그램이 fflush()를 호출하면 데이터가 손실됩니다.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *f = fopen("/dev/null", "w");
    int i;
    int written = 0;
    char *buf = malloc(100000);
    setbuffer(f, buf, 100000);
    for (i = 0; i < 1000; i++)
    {
        written += fprintf(f, "Number %d\n", i);
    }
    for (i = 0; i < written; i++) {
        printf("%c", buf[i]);
    }
}

인메모리 파일 작성 방법에 대한 간단한 예를 작성했습니다.

#include <unistd.h> 
#include <stdio.h> 

int main(){
  int p[2]; pipe(p); FILE *f = fdopen( p[1], "w" );

  if( !fork() ){
    fprintf( f, "working" );
    return 0;
  }

  fclose(f); close(p[1]);
  char buff[100]; int len;
  while( (len=read(p[0], buff, 100))>0 )
    printf(" from child: '%*s'", len, buff );
  puts("");
}

fmemopen은 버퍼에서 FILE을 생성할 수 있습니다.이것을 이해하시겠습니까?

매뉴얼에 기재되어 있는TiXMLPrinterCStr 방식을 사용할 수 있습니다.

TiXmlPrinter는 다음과 같은 경우에 유용합니다.

  1. 메모리로 인쇄(특히 비 STL 모드)
  2. 제어 형식(행 끝 등)

https://github.com/Snaipe/fmem은 다양한 플랫폼/버전별 메모리 스트림 구현용 래퍼입니다.

다음의 실장을 순서대로 시행합니다.

  • open_memstream 입니다.
  • fopen cookie, 다이나믹 버퍼가 증가하고 있습니다.
  • funopen, 다이나믹 버퍼가 증가하고 있습니다.
  • WinAPI 임시 메모리 백업 파일입니다.

사용 가능한 다른 평균이 없는 경우 fmem은 tmpfile()로 폴백합니다.

언급URL : https://stackoverflow.com/questions/539537/how-to-write-to-a-memory-buffer-with-a-file

반응형