Esempio n. 1
0
int main(int argc, char const *argv[]) {
  double tf = 10, t0, dt;
  double g = 9.8, l = 1, ko, kw;
  double o0 = M_PI/4, w0 = 0, o1, w1;

  int n = 100000;

  dt = (tf - t0)/n;
  printf("t\ttheta\tomega\n");
  printf("%f\t%f\t%f\n", t0, o0, w0);

  while (t0 <= tf) {
    ko = fo(w0);
    kw = fw(o0);

    o1 = o0 + dt*fo(w0 + 0.5*dt*ko);
    w1 = w0 - dt*fw(o0 + 0.5*dt*kw);

    o0 = o1;
    w0 = w1;
    t0 += dt;

    printf("%f\t%f\t%f\n", t0, o0, w0);
  }
  return 0;
}
Esempio n. 2
0
bool FileCopy(const char *oldname, const char *newname)
{
#if defined(PLATFORM_WIN32)
	if(IsWinNT())
		return UnicodeWin32().CopyFileW(ToSystemCharsetW(oldname), ToSystemCharsetW(newname), false);
	else
		return CopyFile(ToSystemCharset(oldname), ToSystemCharset(newname), false);
#elif defined(PLATFORM_POSIX)
	FileIn fi(oldname);
	if(!fi.IsOpen())
		return false;
	FileOut fo(newname);
	if(!fo.IsOpen())
		return false;
	CopyStream(fo, fi, fi.GetLeft());
	fi.Close();
	fo.Close();
	if(fo.IsError())
	{
		unlink(newname);
		return false;
	}
	FileSetTime(newname, FileGetTime(oldname));
	return true;
#else
	#error
#endif//PLATFORM
}
Esempio n. 3
0
static void saveMotions(
        int frameCount, const std::vector<Mat> &motions, const std::vector<Mat> &stabilizationMotions)
{
    std::ofstream fm("log_motions.csv");
    for (int i = 0; i < frameCount - 1; ++i)
    {
        Mat_<float> M = at(i, motions);
        fm << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "
           << M(1,0) << " " << M(1,1) << " " << M(1,2) << " "
           << M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;
    }
    std::ofstream fo("log_orig.csv");
    for (int i = 0; i < frameCount; ++i)
    {
        Mat_<float> M = getMotion(0, i, motions);
        fo << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "
           << M(1,0) << " " << M(1,1) << " " << M(1,2) << " "
           << M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;
    }
    std::ofstream fs("log_stab.csv");
    for (int i = 0; i < frameCount; ++i)
    {
        Mat_<float> M = stabilizationMotions[i] * getMotion(0, i, motions);
        fs << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "
           << M(1,0) << " " << M(1,1) << " " << M(1,2) << " "
           << M(2,0) << " " << M(2,1) << " " << M(2,2) << std::endl;
    }
}
Esempio n. 4
0
 void test_read_standard_workbook_from_fileobj()
 {
     auto path = PathHelper::GetDataDirectory("/genuine/empty.xlsx");
     std::ifstream fo(path, std::ios::binary);
     auto wb = xlnt::load_workbook(path);
     TS_ASSERT_DIFFERS(standard_workbook(), nullptr);
 }
Esempio n. 5
0
bool ModelContact::salvare(CString fisier)
{
	char fis[200];
	strcpy(fis,fisier.GetBuffer());
	std::ofstream fo(fis,std::ios::app);
	fo.flush();

	if(!fo.is_open())
		return false;

	CString linie;
	linie.Empty();
	switch(getTip())
	{
		case Friend:
			linie=_T("f"); break;
		case Colleague:
			linie=_T("c"); break;
		case Acquaintance:
			linie=_T("a"); break;
	}
	linie.Append("|");
	linie.Append(nume);
	linie.Append("|");
	linie.Append(prenume);
	linie.Append("|");
	linie.Append(nr_tel);
	linie.Append("|");
	linie.Append(atribut);

	char lin[300];
	strcpy(lin,linie.GetBuffer());
	fo<<lin<<"\n";
	return true;
}
Esempio n. 6
0
void checkFunnelObstacleFind1()
{
  FunnelObstacle fo(8.0f, 10.0f, 10.0f);

  // pick up some points
  const float eps = 0.1;
  const float my0 = -4.0;
  //const float yPlaneUp = 4.0;
  assertTrue(fo.sample(0, my0).second < eps);
  assertTrue(fo.isInside(0, my0 + 1) == true);
  assertTrue(fo.isInside(0, my0 - 1) == false);

  // check on the points from the border
  size_t szForEvery = 20;
  float h = 10.0 / szForEvery;
  for (size_t ix = 0; ix < szForEvery; ++ix) {
    float x = ix * h - 5;
    float y = 0.0;
    if (x > -1.9 && x <= 1.9)
      assertTrue(fo.isInside(x, y));
    if (x < -2.1 || x >= 2.1)
      assertTrue(!fo.isInside(x, y));
  }

    float x = 0.0;
    if (y > -3.9 && y <= 3.9)
      assertTrue(fo.isInside(x, y));
    if (y < -4.1 || y >= 4.1)
      assertTrue(!fo.isInside(x, y));
  }
Esempio n. 7
0
void ImageView::savePNG(const QString& text) {
    QSettings settings;
    QString inputPath = window()->windowFilePath();
    QString outputPath = settings.value("savename", inputPath).toString();

    QString filename;
    QFileInfo fi(inputPath);
    QFileInfo fo(outputPath);
    if (!fi.baseName().isEmpty()) {
        QFileInfo fn(fo.dir(), fi.baseName() + "-out.png");
        filename  = fn.absoluteFilePath();
    } else {
        filename  = fo.absolutePath();
    }

    filename = QFileDialog::getSaveFileName(this, "Save PNG", filename, 
        "PNG Format (*.png);;All files (*.*)");
    if (!filename.isEmpty()) {
        QImage tmp(image());
        if (!text.isEmpty()) tmp.setText("Description", text);
        if (!tmp.save(filename)) {
            QMessageBox::critical(this, "Error", QString("Saving PNG '%1' failed!").arg(filename));
            return;
        }
        settings.setValue("savename", filename);
    }
}
Esempio n. 8
0
void foo2() {
  ADL::Outer o;
  ADL::Inner i;
  fo(o);
  fi(i);
  fi2(i);
}
Esempio n. 9
0
bool KMapDataManager::createMap(const char* mapName, int width, int height)
{
	KMapData* mapData = this->getMapData(mapName);
	if(mapData) return false;

	JG_C::KString<512> filepath = this->_getFilePath(mapName);
	FILE* f = JG_F::KFileUtil::OpenFileForce(filepath.c_str(), "r+b");
	if(!f) return false;

	KOutputFileStream fo(f);

	KMapData mdt;
	if(!mdt.initialize(width, height))
	{
		fclose(f);
		return false;
	}

	if(!mdt.save(fo))
	{
		fclose(f);
		return false;
	}

	DWORD size = fo.tell();
	JG_F::KFileUtil::SetFileSize(f, size);
	fclose(f);

	MapDesc desc;
	desc.mapName = KBuffer64k::WriteData(mapName, strlen(mapName)+1);
	desc.mapData = mdt;
	m_mapByName[desc.mapName] = desc;

	return true;
}
Esempio n. 10
0
// Test parsing a bunch of valid file output options
TEST_VM(LogFileOutput, parse_valid) {
  const char* valid_options[] = {
    "", "filecount=10", "filesize=512",
    "filecount=11,filesize=256",
    "filesize=256,filecount=11",
    "filesize=0", "filecount=1",
    "filesize=1m", "filesize=1M",
    "filesize=1k", "filesize=1G"
  };

  // Override LogOutput's vm_start time to get predictable file name
  LogFileOutput::set_file_name_parameters(0);
  char expected_filename[1 * K];
  int ret = jio_snprintf(expected_filename, sizeof(expected_filename),
                         "testlog.pid%d.1970-01-01_01-00-00.log",
                         os::current_process_id());
  ASSERT_GT(ret, 0) << "Buffer too small";

  for (size_t i = 0; i < ARRAY_SIZE(valid_options); i++) {
    ResourceMark rm;
    stringStream ss;
    {
      LogFileOutput fo(name);
      EXPECT_STREQ(name, fo.name());
      EXPECT_TRUE(fo.initialize(valid_options[i], &ss))
        << "Did not accept valid option(s) '" << valid_options[i] << "': " << ss.as_string();
    }
    remove(expected_filename);
  }
}
Esempio n. 11
0
// Test parsing a bunch of invalid file output options
TEST_VM(LogFileOutput, parse_invalid) {
  const char* invalid_options[] = {
    "invalidopt", "filecount=",
    "filesize=,filecount=10",
    "fileco=10", "ilesize=512",
    "filecount=11,,filesize=256",
    ",filesize=256,filecount=11",
    "filesize=256,filecount=11,",
    "filesize=-1", "filecount=0.1",
    "filecount=-2", "filecount=2.0",
    "filecount= 2", "filesize=2 ",
    "filecount=ab", "filesize=0xz",
    "filecount=1MB", "filesize=99bytes",
    "filesize=9999999999999999999999999"
    "filecount=9999999999999999999999999"
  };

  for (size_t i = 0; i < ARRAY_SIZE(invalid_options); i++) {
    ResourceMark rm;
    stringStream ss;
    LogFileOutput fo(name);
    EXPECT_FALSE(fo.initialize(invalid_options[i], &ss))
      << "Accepted invalid option(s) '" << invalid_options[i] << "': " << ss.as_string();
  }
}
Esempio n. 12
0
int main(int argc, char** argv)
{
	if (argc < 2) {
		printf("specify filename\n");
		return 1;
	}
	
	FILE* f = fopen(argv[1], "rb");
	if (!f) {
		printf("failed to open file : %s\n", argv[1]);
		return 1;
	}
	File fo(f);
	ImageInfo imageInfo;
	ReadImageInfo(fo, imageInfo);
	
	size_t width = imageInfo.width;
	size_t height = imageInfo.height;
	assert(imageInfo.bitsPerSample == 8 && imageInfo.samplesPerPixel == 1);
	const size_t size = width * height;
	unsigned char* pSrc = (unsigned char*) _aligned_malloc(size, 64);
	unsigned char palettes[256 * 4];
	ReadImageData(fo, pSrc, width, palettes);
	fclose(f);
	
	for (size_t i=0; i<size; ++i) {
		pSrc[i] = palettes[4 * pSrc[i]];
	}

	int radius = 1.1 * 256;
	
//	typedef void (*BoxBlurFunc)(const uint8_t* src, uint8_t* dst, size_t count, uint8_t radius);
//	BoxBlurFunc pBlurFunc = &BoxBlur_1stOrder;
//	BoxBlurFunc pBlurFunc = &BoxBlur_2ndOrder;
//	BoxBlurFunc pBlurFunc = &BoxBlur_3rdOrder;

	typedef void (*BoxBlurFunc)(const uint8_t* src, uint8_t* dst, size_t count, uint16_t radius);
	BoxBlurFunc pBlurFunc = &SubPixel_BoxBlur_1stOrder;

	size_t longSideLen = max(width, height);
	unsigned char* pWork = (unsigned char*) _aligned_malloc(longSideLen*longSideLen, 64);
	unsigned char* pWork2 = (unsigned char*) _aligned_malloc(longSideLen*longSideLen, 64);
	const unsigned char* pSrcLine = pSrc;
	unsigned char* pDstLine = pWork;
	for (size_t i=0; i<height; ++i) {
		pBlurFunc(pSrcLine, pDstLine, width, radius);
		OffsetPtr(pSrcLine, width);
		OffsetPtr(pDstLine, longSideLen);
	}
	transpose(pWork, pWork2, width, height, longSideLen, longSideLen);
	pSrcLine = pWork2;
	pDstLine = pWork;
	for (size_t i=0; i<width; ++i) {
		pBlurFunc(pSrcLine, pDstLine, height, radius);
		OffsetPtr(pSrcLine, longSideLen);
		OffsetPtr(pDstLine, longSideLen);
	}
	transpose(pWork, pWork2, height, width, longSideLen, longSideLen);
	return 0;
}
Esempio n. 13
0
void main()
{
	clrscr();
	Item I;
	char ch='y', fit[4][8], chi[60];
	int nof, i;
	strcpy(chi, "c:\\animart");
	while((ch == 'y') || (ch == 'Y'))
	{
		clrscr();
		cout<<"Enter no. of folders (after \"c:\\animart\\\")\n";
		cin>>nof;
		for( i=0; i<nof; i++)
		{
			cout<<"Enter folder "<<i+1<<" : ";
			cin>>fit[i];
			strcat(chi, "\\");
			strcat(chi, fit[i]);
		}
		clrscr();
		cout<<"\nEnter File Name (without.txt): ";
		cin>>fit[i];
		strcat(chi, "\\");
		strcat(chi, fit[i]);
		strcat(chi, ".txt");
		nof += 1;
		I.itdat(fit[0], fit[1], fit[2], fit[3], nof);
		ofstream fo(chi, ios :: app);
		fo.write((char*)&I, sizeof(I));
		cout<<"Want to Enter more (y/n) ? ";
		cin>>ch;
	}
	getch();
}
Esempio n. 14
0
void writeToNrrd(float* data, int w, int h, int l, const char *name) {
    char buffer[255];
    // Write the header file
    sprintf(buffer,"%s.nhdr",name);
    std::ofstream fo(buffer, std::ios::binary);
    sprintf(buffer,"%s.raw",name);

    fo << "NRRD0004" << std::endl;
    fo << "# Complete NRRD file format specification at: "<< std::endl;
    fo << "# http://teem.sourceforge.net/nrrd/format.html"<< std::endl;
    fo << "content: resample "<< std::endl;
    fo << "type: float"<< std::endl;
    fo << "dimension: 3"<< std::endl;
    fo << "space: left-posterior-superior"<< std::endl;
    fo << "sizes: " <<w << " " << h << " " << l << std::endl;
    fo << "space directions: (1,0,0) (0,1,0) (0,0,1) "<< std::endl;
    fo << "centerings: cell cell cell"<< std::endl;
    fo << "kinds: domain domain domain"<< std::endl;
    fo << "endian: little"<< std::endl;
    fo << "encoding: raw"<< std::endl;
    fo << "space origin: (0,0,0)"<< std::endl;
    fo << "data file: " << buffer << std::endl;
    fo.close();

    unsigned int len = w * h * l;
    std::ofstream fo1(buffer, std::ios::binary);
    fo1.write((char*)data, len * sizeof(float));
    fo1.close();
}
Esempio n. 15
0
void EvalFileCopy(const void *mode, qCtx *ctx, qStr *out, qArgAry *args)
{
	VALID_ARGC("copy", 2, 2);

	CStr from = (*args)[0];
	CStr to = (*args)[1];

	FILE *fpi = safe_fopen(ctx, from, "rb");

	if (!fpi) {
		ctx->ThrowF(out, 603, "Failed to open file for reading.");
		return;
	}
	FILE *fpo = safe_fopen(ctx, to, "wb");
	if (!fpo) {
		ctx->ThrowF(out, 602, "Failed to open file for copy.");
		return;
	}

	qStrFileO fo(fpo, true);
	qStrFileI fi(fpi, true);
	CStr s;
	while (!(s = fi.GetS()).IsEmpty()) {
		fo.PutS(s);
	}
}
Esempio n. 16
0
/******************
      ÑÓʱms
******************/
void delay_ms(uint t){
  int i,j,k;
  for(k=0;k<t;k++)
    for(i=0;i<27;i++)
      for(j=0;j<50;j++)
        fo(dd )
        ;
}
Esempio n. 17
0
bool PostscriptDialog::checkParameter()
{
	QString infile = m_PostscriptDialog.m_edInfile->lineEdit()->text();
	if (infile.isEmpty()) {
		showError(i18n("No input file is given."));
		return false;
	}

	QFileInfo fi(infile);
	QString suffix = fi.completeSuffix();
	if (suffix != "ps" && suffix != "ps.gz") {
		showError(i18n("Unknown file format: only '.ps' and '.ps.gz' are accepted for input files."));
		return false;
	}

	if (!fi.exists()) {
		showError(i18n("This input file does not exist."));
		return false;
	}

	// check parameter
	int index = m_PostscriptDialog.m_cbTask->currentIndex();
	if (m_PostscriptDialog.m_edParameter->text().isEmpty()) {
		if (index == PS_PSSELECT_FREE) {
			showError( i18n("psselect needs some parameters in this mode.") );
			return false;
		} else if (index == PS_PSTOPS_FREE) {
			showError( i18n("pstops needs some parameters in this mode.") );
			return false;
		}
	}

	QString outfile = m_PostscriptDialog.m_edOutfile->lineEdit()->text();
	if (outfile.isEmpty() && !m_PostscriptDialog.m_cbView->isChecked()) {
		showError(i18n("You need to define an output file or select the viewer."));
		return false;
	}

	if (! outfile.isEmpty()) {
		QFileInfo fo(outfile);
		if (fo.completeSuffix() != "ps") {
			showError(i18n("Unknown file format: only '.ps' is accepted as output file."));
			return false;
		}
	
		if (infile != outfile && fo.exists()) {
			QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName());
			if (KMessageBox::questionYesNo(this,
			                               "<center>" + s + "</center>",
			                               "Postscript tools") == KMessageBox::No) {
				return false;
			}
		}
	}
	
	return true;
}
Esempio n. 18
0
 template< class T > bool save( const T& t, const char * file ) {
     try {
         std::ofstream fo( file );
         return adportable::binary::serialize<>()(t, fo);
     } catch ( std::exception& ex ) {
         std::cout << "\t" << boost::diagnostic_information( ex );
         BOOST_THROW_EXCEPTION(ex);
     }
     return false;
 }
Esempio n. 19
0
// Test for overflows with filesize
TEST_VM(LogFileOutput, filesize_overflow) {
  char buf[256];
  int ret = jio_snprintf(buf, sizeof(buf), "filesize=" SIZE_FORMAT "K", SIZE_MAX);
  ASSERT_GT(ret, 0) << "Buffer too small";

  ResourceMark rm;
  stringStream ss;
  LogFileOutput fo(name);
  EXPECT_FALSE(fo.initialize(buf, &ss)) << "Accepted filesize that overflows";
}
Esempio n. 20
0
//--------
// ostream
//--------
void XEMLabelDescription::saveNumericValues(string fileName){
  //if (_fileName==""){
  ofstream fo(fileName.c_str(), ios::out);
  _label->edit(fo);
  _fileName = fileName;
  //}
  /* else : if _fileName!="", labelDescription has been created by a XML file.
     In this case, the numeric file already exists.
  */
}
Esempio n. 21
0
int main()
{
	fo("pprime.in","r",stdin);
	fo("pprime.out","w",stdout);
	ll a,b;
	scanf("%lld %lld",&a,&b);
	int i=1;
	while(p[i]<a)
	{
		i++;
	}	
	for(int j=i;j<=781;j++)
	{
		if(p[j]>b)break;
		if(pp(p[j]))printf("%lld\n",p[j]);
	}

    return 0;
}
Esempio n. 22
0
void checkFunnelObstacleReadWrite()
{
  std::string inputFileName = "bla.dat";
  FunnelObstacle fo(16.0f, 20.0f, 40.0f, 128, 128);
  fo.write(inputFileName);

  FunnelObstacle fIn(16.0f, 20.0f, 40.0f, 128, 128, inputFileName);
  assertTrue(fIn == fo);
  printOk();
}
Esempio n. 23
0
void Mesh::save(const std::string& fname) const
{
    std::ofstream fo(fname.c_str());
    {
        StreamBlockWriter w("MeshDescription", fo);
        w.write("subCount", getSubCount());
    }
    for (int i = 0; i < getSubCount(); ++i) {
        fo << *sub(i);
    }
}
Esempio n. 24
0
void phillip_main_t::learn(const lf::input_t &input)
{
    auto get_path_for_gold = [this](const std::string &key) -> std::string
    {
        std::string path = param(key);
        if (not path.empty())
        {
            int idx = path.rfind('.');
            if (idx > 0)
                path = path.substr(0, idx) + ".gold" + path.substr(idx);
            else
                path += ".gold";
        }
        return path;
    };

    reset_for_inference();
    set_input(input);

    auto begin = std::chrono::system_clock::now();

    erase_flag("get_pseudo_positive");

    execute_enumerator();
    execute_convertor();
    execute_solver();

    set_flag("get_pseudo_positive");

    execute_convertor(
        &m_ilp_gold, &m_time_for_convert_gold,
        get_path_for_gold("path_ilp_out"));
    execute_solver(
        &m_sol_gold, &m_time_for_solve_gold,
        get_path_for_gold("path_sol_out"));

    util::xml_element_t elem("learn", "");
    m_ilp_convertor->tune(m_sol.front(), m_sol_gold.front(), &elem);

    m_time_for_learn = util::duration_time(begin);

    std::ofstream *fo(NULL);
    if ((fo = _open_file(param("path_out"), std::ios::out | std::ios::app)) != NULL)
    {
        if (not flag("omit_proof_graph_from_xml"))
        {
            m_sol.front().print_graph(fo);
            m_sol_gold.front().print_graph(fo);
        }
        elem.print(fo);
        delete fo;
    }
}
Esempio n. 25
0
void MouseHandler::WriteResultsToFile(string nameOfFile, string nameOfAlgo, Ellipsoid* el, bool multiDim)
{
	Window* window = Window::Create();
	if (multiDim)
		Helper::WritePoints(*window->MultiDimVert, nameOfFile);
	else
		Helper::WritePoints(*window->vertexes, nameOfFile);

	ofstream fo(nameOfFile, ios::app);
	WriteEllipse(fo, nameOfAlgo, el->Eigenvectors(), el->Axes(), el->Dim(), el->Centre().Coords());
	fo.close();
}
Esempio n. 26
0
void TestVector() {
    SpacePoint vec1(10), vec2, tmp;
    //	DataVector<double> vec1(10),vec2,tmp;
    vec1 = 5;
    //	(SavableClass&)vec2=(SavableClass&)vec1;
    vec1[5] = 55;
    vec2 = vec1 = 10;
    fcout << vec2 << "\n" << vec1 << "\n";
    fcout << "vec1 " << vec1 << "\n vec2 " << vec2 << "\n";
    tmp = vec1 + vec2;
    //	DataVector<double> tmp=vec1+vec2;
    fcout << tmp << "\n";
    fcout << "sum " << vec1 + vec2 << " \n min " << vec2 - vec1 << " \n mul "
          << vec1 * vec2 << "\n";
    {
        FilterTextOut fo("Test1", DataSource::Memory);
        vec2 = 100;
        fo << vec2;
        FilterTextIn fi("Test1", DataSource::Memory);
        fi >> vec1;
    }
    fcout << "vec1" << vec1 << "\n vec2" << vec2 << "\n";
    DataVector<SpacePoint> dat(10);
    dat[0].SetDim(10);
    dat[0] = 5;
    for(int k = 1; k < 9; k++)
        dat[k] = dat[0];
    fcout << dat << "\n" << (void *)&vec2 << "\n";
    void *tmpv = NULL;
    FilterTextOut fo("Test1", DataSource::Disk);
    fo << (void *)&vec1 << 10;
    //fo<<10;
    fo.CloseBuf();
    FilterTextIn fi("Test1", DataSource::Disk);
    int tmp_int;   //fi>>tmp_int;fcout<<tmp_int;
    fi >> tmpv >> tmp_int;
    fcout << tmpv << tmp_int;
}
Esempio n. 27
0
static void genDisassemble(const string& fname)
{
    ofstream fo(fname.c_str());

    fo << "_global:\n";
    CodeManager::instance()->getFuncPreMain()->getCodeSeq()->disassemble(fo);

    for (auto name : CodeManager::instance()->getFuncNames()) {
        if (auto p = dynamic_cast<ASTFunction*>(CodeManager::instance()->getFunc(name).get())) {
            fo << name << ":\n";
            p->getCodeSeq()->disassemble(fo);
        }
    }
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QStringList args = a.arguments();
    if (args.size() < 3)
    {
        qCritical("Usage: %s <input.edif> <output.xml>", argv[0]);
        return 1;
    }

    /*QFile fi(args[1]);
    if (!fi.open(QFile::ReadOnly))
    {
        qCritical("Can't open EDIF file");
        return 1;
    }

    lispParserInit(&fi);
    QVariantList top = lispParse().toList();*/

    QVariantList top = parseLispFile(args[1]);

    //fi.close();

    QFile fo(args[2]);
    if (!fo.open(QFile::WriteOnly | QFile::Truncate))
    {
        qCritical("Can't open XML file");
        return 1;
    }

    QXmlStreamWriter stream(&fo);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();

    writeTop(stream, top);

    /*stream.writeStartElement("bookmark");
    stream.writeAttribute("href", "http://qt-project.org/");
    stream.writeTextElement("title", "Qt Project");
    stream.writeEndElement(); // bookmark*/

    stream.writeEndDocument();

    fo.close();

    return 0;
}
Esempio n. 29
0
static void testReaderAll2 () {
  do {

  QFile fl("onex.json");
  if (!fl.open(QIODevice::ReadOnly)) {
    fprintf(stderr, "ERROR: can't open input file!\n");
    return;
  }

  const uchar *fmap = (const uchar *)(fl.map(0, fl.size()));
  int len = fl.size();
  const uchar *sj = K8JSON::skipBlanks(fmap, &len);
  if (!sj) {
    fprintf(stderr, "ERROR: invalid JSON file!\n");
    break;
  }
  uchar qch = *sj;
  if (qch != '[' && qch != '{') {
    fprintf(stderr, "ERROR: invalid JSON file!\n");
    break;
  }

  int cnt = 0;
  QTime st;
  st.start();

  QVariant val;
  sj = K8JSON::parseRecord(val, sj, &len);
  if (!sj) {
    fprintf(stderr, "ERROR: invalid JSON file!\n");
    break;
  }
  qDebug() << "time taken (ms):" << st.elapsed();
  //qDebug() << val;

  QByteArray bo;
  if (!K8JSON::generate(bo, val)) {
    fprintf(stderr, "ERROR: can't generate JSON file!\n");
    break;
  }
  QFile fo("000.json");
  if (fo.open(QIODevice::WriteOnly)) {
    fo.write(bo);
    fo.write("\n");
    fo.close();
  }

  } while (0);
}
Esempio n. 30
0
void WriteCSV(const void *mode, bool forceQuoted, qCtx *ctx, qStr *out, qArgAry *args)
{
	CStr path = ctx->ParseStr((*args)[0]);

	if (path.IsEmpty())
		return;
	
	FILE *fp = safe_fopen(ctx, path, (const char *) mode);

	if (!fp) {
		ctx->ThrowF(out, 601, "Failed to open file for writing. %y", GetLastError());
		return;
	}

	qStrFileO fo(fp, true);
	CStr bo;
	qStrBuf quot;

	qCtxTmp sub(ctx);
	sub.MapObj(fp, EvalFileFlush,"flush");

	int i;
	char *p, *b;
	for (i = 1; i < args->Count(); ++i) {
		bo = sub.ParseStr((*args)[i]);
		quot.Clear();

		b = bo.GetBuffer();
		if ((p = strchr((const char *)b, '"'))) {
			quot.PutC('"');
			do {
				quot.PutS(b, p - b + 1);
				quot.PutS('"');
			} while ((p = strchr((const char *)b, '"')));
			quot.PutC('"');
			fo.PutS(quot);
		} else if (forceQuoted || (p = strchr((const char *)b, ','))) {
			quot.PutC('"');
			quot.PutS(bo);
			quot.PutC('"');
			fo.PutS(quot);
		} else
			fo.PutS(bo);
		if (i < (args->Count()-1) ) {
			fo.PutC(',');
		}
	}
	fo.PutC('\n');
}