Herzlich Willkommen, lieber Gast!
  Sie befinden sich hier:

  Forum » C / C++ (ANSI-Standard) » Textdatei komplett in einer Variable speichern

Forum | Hilfe | Team | Links | Impressum | > Suche < | Mitglieder | Registrieren | Einloggen
  Quicklinks: MSDN-Online || STL || clib Reference Grundlagen || Literatur || E-Books || Zubehör || > F.A.Q. < || Downloads   

Autor Thread - Seiten: > 1 <
000
18.12.2004, 19:20 Uhr
~dcdead
Gast


Hallo,

Ich habe ne normale Textdatei mit einer bestimmten Anzahl an Zeilen. Jetzt würde ich den Inhalt der Datei gerne komplett in einer Variable speichern, um ihn dann weiterverwenden zu können. Hab leider grad gar keine Ahnung wie ich das machen soll. Ich habs mal so gemacht:


C++:
    blabla[255]; ;
  
    FILE *fp = fopen("/tmp/test.txt", "r");


    if ( fp )
    {
        fgets(blabla,255,fp);
        fclose(fp);
    }




Hoffe jemand kann mir auf die Sprünge helfen
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
001
18.12.2004, 19:42 Uhr
mike
Pinguinhüpfer
(Operator)


Hi!
Hmm. Du musst die größe der Datei (also die Anzahl der Zeichen bestimmen), dann ein char array mit malloc allokieren und mit fgets(blabla,sizeof(blabla),fp); einlesen.

mfg
--
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
002
24.12.2004, 20:42 Uhr
morbid



versuchs mal mit nem string
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
003
25.12.2004, 01:53 Uhr
Pablo
Supertux
(Operator)


@morbid: daraus erkenne ich dass er C benutzt, also gibt es kein std::string, das er benutzen kann.

Du kannst folgednes benutzen:


C++:
/***************************************************************************
                          safestring.h  -  description
                             -------------------
    begin                : 13.03.04
    copyright            : (C) 04 by Pablo
    email                : rex@supertux.homelinux.org
***************************************************************************/


/***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************/


/* This is a small couple of tools that helps to handle with C char* (strings)
safely */


#ifndef SAFESTRING_H
#define SAFESTRING_H

/* include useful stuf */

#include <string.h>
#include <stdlib.h>


/* define error constants */

/* don't declare this variable by yourself. This variable
will be declared in safestring.c.

You have always to set ss_errno to 0 or SS_NO_ERROR by yourself,
if you want to use this variable. If a function ends successfully
then ss_errno won't be SS_NO_ERROR; this variable is set only when
an error is generated.

List of ERRORS

Name              || value || Description
=========================================
SS_NO_ERROR          0        describes the state of no error
SS_NO_MEM         1          cannot execute malloc because of the memory
SS_NO_EXPAND         2        cannot execute realloc and expand the buffer
SS_NULL_BUFFER       3        you passed a NULL buffer, when a string is required
                  or a not NULL pointer is required

*/

extern int ss_errno;

#define SS_NO_ERROR 0
#define SS_NO_MEM 1
#define SS_NO_EXPAND 2
#define SS_NULL_BUFFER 3

/* functions */

/* NOTE: The memory areas (between *dest and src) may not overlap */

char* insert_char(char** dest, char c);
/*

   INPUT:

   dest: pointer to a char* variable
   c: new character that you want to insert

   if dest points to a NULL char*, then insert_char will
   allocate 2 bytes and insert c. If dest doesn't point
   to a NULL char* then insert_char will assume that you
   dest points to a variable that was already allocated by malloc
   and/or one of this functions. NOTE: If dest points to a not NULL
   char* that wasn't allocated by malloc, then you may have an unexpected
   behaviour.

   If you the new character is \0 the function won't do anything.

   NOTE: the contents of the variable that is pointed by dest will be change

   OUTPUT: returns a pointer to the string that contains the new character,
   NULL if there was an error. The returned string is a 0-terminated string,
   there is no need to insert \0, in fact nothing will happen if you try, you will get
   a NULL pointer
*/


char* insert_string(char** dest, const char* src);
/*

   INPUT:

   dest: pointer to a char* variable
   src: a 0-terminated pointer to a string

   if dest points to a NULL char*, then insert_char will
   allocate 2 bytes and append src. If dest doesn't point
   to a NULL char* then insert_char will assume that you
   dest points to a variable that was already allocated by malloc
   and/or one of this functions. NOTE: If dest points to a not NULL
   char* that wasn't allocated by malloc, then you may have an unexpected
   behaviour.

   If you the new character is \0 the function won't do anything.

   NOTE: the contents of the variable that is pointed by dest will be change

   OUTPUT: returns a pointer to the string that contains the new character,
   NULL if there was an error. The returned string is a 0-terminated string.
   There is no need that you insert an empty string, if you try it then the
   functions won't do anything and you get NULL.
*/


char* str2sstr(const char* src);
/*
   INPUT:

   src: a 0-terminated pointer to a string

   This function creates a new safe string so that you
   can use this functions. The input won't be modified.

   OUTPUT: returns a pointer to the string that contains the new character,
   NULL if there was an error. The returned string is a 0-terminated string.
*/


void clear_sstr(char* src);
/* this functions clears a safe string */

#endif




C++:
/***************************************************************************
                          safestring.c  -  description
                             -------------------
    begin                : 13.03.04
    copyright            : (C) 04 by Pablo
    email                : rex@supertux.homelinux.org
***************************************************************************/


/***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************/


#include "safestring.h"

int ss_errno;

char* insert_char(char** dest, char c)
{
    char* tmp;
    size_t len;

    if(!c) return NULL;

    if(!dest) {
        ss_errno = SS_NULL_BUFFER;
    return NULL;
    }

    if(!*dest) {
        tmp = malloc(2);
    if (!tmp) {
        ss_errno = SS_NO_MEM;
        return NULL;
    }
    *tmp = c;
    *(tmp+1) = 0;
    *dest = tmp;
    } else {
        len = strlen(*dest)+2; /* only 2, because the old *dest is a 0-terminated string */
    tmp = realloc(*dest, len);

    if(!tmp) {
        ss_errno = SS_NO_EXPAND;
        return NULL;
    }

    if(tmp != *dest)
        *dest = tmp;

    *(tmp+len-2) = c;
    *(tmp+len-1) = 0;
    }

    return *dest;
}

char* insert_string(char** dest, const char* src)
{
    char* tmp;
    size_t len,olen;

    if(!src) {
        ss_errno = SS_NULL_BUFFER;
    return NULL;
    }

    if(!*src) {
        return NULL;
    }

    if(!dest) {
        ss_errno = SS_NULL_BUFFER;
    return NULL;
    }

    if(!*dest) {
        tmp = malloc(strlen(src)+1);

    if(!tmp) {
        ss_errno = SS_NO_MEM;
        return NULL;
    }

    strcpy(tmp,src);
    *dest = tmp;
    } else {

        olen = strlen(*dest);
        len = olen+strlen(src)+1;
    tmp = realloc(*dest, len);

    if(!tmp) {
        ss_errno = SS_NO_EXPAND;
        return NULL;
    }

    if(tmp != *dest)
        *dest = tmp;
    
    strcpy((*dest+olen), src);
    }

    return *dest;
}

char* str2sstr(const char* src)
{
    char* tmp;

    if(!src) {
        ss_errno = SS_NULL_BUFFER;
    return NULL;
    }

    tmp = malloc(strlen(src)+1);

    if(!tmp) {
        ss_errno = SS_NO_MEM;
    return NULL;
    }

    strcpy(tmp,src);

    return tmp;
}

void clear_sstr(char* src)
{
    free(src);
}




C++:
/* example1.c

reads the file README ans saves character by character in a char*
If you don't know the size of the file, you cannot allocate enough memory, or you
have to work with realloc and this is not comfortable. */


#include <stdio.h>
#include "safestring.h"

int main()
{
    char* file_in_string=NULL;
    char* tmp;
    FILE* fbuffer;
    int c;

    ss_errno = SS_NO_ERROR; /* set no error flag */

    if(NULL==(fbuffer = fopen("README", "r"))) {
        fprintf(stderr, "File README cannot be opened.\n");
    return 1;
    }

    while(EOF != (c=fgetc(fbuffer))) {
        tmp = insert_char(&file_in_string, c);
    if(!tmp) {
        /* some error was produced */
        switch(ss_errno) {
            case SS_NO_MEM:
        case SS_NO_EXPAND:
            fprintf(stderr, "No more memory available! All readen characters are printed on stdout\n");
        }

        break;
    }
    }

    
    printf("================= README ======================\n");
    printf("%s\n", file_in_string);
    printf("================= README ======================\n");


    fclose(fbuffer);
    clear_sstr(file_in_string);

    return 0;
}


--
A! Elbereth Gilthoniel!
silivren penna míriel
o menel aglar elenath,
Gilthoniel, A! Elbereth!

Dieser Post wurde am 25.12.2004 um 01:54 Uhr von Pablo editiert.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
004
25.12.2004, 10:01 Uhr
(un)wissender
Niveauwart


Hach, was ist std::string oder std::vector doch schön...
--
Wer früher stirbt ist länger tot.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
005
25.12.2004, 11:42 Uhr
0xdeadbeef
Gott
(Operator)


Ich hab grad keinen Compiler zur Hand, von daher ohne Gewähr, aber ich denke, dass das hier funzen sollte:

C++:
#include <stdio.h>

int main(void) {
    FILE *fd = fopen("test.txt");
    char *str;
    int len;

    fseek(fd, 0L, SEEK_END);
    len = ftell(fd);
    rewind(fd);

    str = calloc(len + 1, sizeof(char));
    fread(str, sizeof(char), len, fd);

    puts(str);

    free(str);

    return 0;
}


--
Einfachheit ist Voraussetzung für Zuverlässigkeit.
-- Edsger Wybe Dijkstra

Dieser Post wurde am 25.12.2004 um 11:44 Uhr von 0xdeadbeef editiert.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
Seiten: > 1 <     [ C / C++ (ANSI-Standard) ]  


ThWBoard 2.73 FloSoft-Edition
© by Paul Baecher & Felix Gonschorek (www.thwboard.de)

Anpassungen des Forums
© by Flo-Soft (www.flo-soft.de)

Sie sind Besucher: