Lecture et ecriture d´un fichier en C++

Fermé
kamit Messages postés 6 Date d'inscription mardi 16 juin 2009 Statut Membre Dernière intervention 16 décembre 2009 - 9 déc. 2009 à 13:07
kamit Messages postés 6 Date d'inscription mardi 16 juin 2009 Statut Membre Dernière intervention 16 décembre 2009 - 16 déc. 2009 à 02:13
Bonjour,
J´aimerai en C++ lire un fichier, qui contient l´information suivante: [QWEAS]-A-D-F-{DE}-X-GTRA
Apres la lecture, je dois reecrire l´information dans un nouveau fichier sous cette forme:
QWEASADFDEXGTRA. En tout([,{,-) doivent etre eliminés.
Comment puis je programmer celà en C++. Merci
A voir également:

9 réponses

didji31320 Messages postés 23 Date d'inscription mardi 8 décembre 2009 Statut Membre Dernière intervention 27 mars 2011 7
9 déc. 2009 à 18:54
Salut kamit,

Voilà un petit pgrm qui va faire ce que tu demande ;)

PS : c'est du C

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


int main (void)
{
    FILE * ficNonTraite;
    FILE * ficTraite;
    char carac;

    ficNonTraite=fopen("fichier_non_traite.txt","r");
    ficTraite=fopen("fichier_traite.txt","w");

    while(feof(ficNonTraite)==0)
    {
        fread(&carac,sizeof(carac),1,ficNonTraite);
        if(carac>='A' && carac<='Z')
        {
            fwrite(&carac,sizeof(carac),1,ficTraite);
        }
    }
    fclose(ficTraite);
    fclose(ficNonTraite);

    system("pause");
    return 0;
}



En espérant t'avoir été utile :)
1
Bonjour,

Voici le code que tu demande, un peu long. Attention, il ne garde QUE les caractères en CAPITALES.
Il crée aussi un fichier nommé 'carac', puis le supprime, mais ne t'en occupe pas, il contient l'alphabet.

Au revoir :)

//Veille à nommer les fichiers comme tu le souhaite, et à indiquer le nombre de caractères. Si tu en mets trop, le programme ne fera rien de spécial. Si tu n'en mets pas assez, le programme s'arrêtera.



#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
char fichierSrc [] = "nom_de_ton_fichier.txt";
char sortieSrc [] = "nom_du_fichier_final.txt";

int ii = 50; // Nombre de caractères de ton fichier initial !!! Mets en plus ! 1000 si tu veux !


char ac;
FILE* fichier = NULL;
FILE* sortie = NULL;
FILE* carac = NULL;
carac = fopen("carac", "a");
fprintf(carac,"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
fclose(carac);
carac = fopen("carac", "r");
char a = fgetc(carac);
char b = fgetc(carac);
char c = fgetc(carac);
char d = fgetc(carac);
char e = fgetc(carac);
char f = fgetc(carac);
char g = fgetc(carac);
char h = fgetc(carac);
char i = fgetc(carac);
char j = fgetc(carac);
char k = fgetc(carac);
char l = fgetc(carac);
char m = fgetc(carac);
char n = fgetc(carac);
char o = fgetc(carac);
char p = fgetc(carac);
char q = fgetc(carac);
char r = fgetc(carac);
char s = fgetc(carac);
char t = fgetc(carac);
char u = fgetc(carac);
char v = fgetc(carac);
char w = fgetc(carac);
char x = fgetc(carac);
char y = fgetc(carac);
char z = fgetc(carac);
fclose(carac);
fichier = fopen(fichierSrc, "r");
sortie = fopen(sortieSrc, "a");
while(ii>0){
ac = fgetc(fichier);
if(ac==a||ac==b||ac==c||ac==d||ac==e||ac==f||ac==g||ac==h||ac==i||ac==j||ac==k||ac==l||ac==m||ac==n||ac==o||ac==p||ac==q||ac==r||ac==s||ac==t||ac==u||ac==v||ac==w||ac==x||ac==y||ac==z){fprintf(sortie,"%c",ac);}
ii--;
}
system("del carac");
fclose(fichier);
fclose(sortie);
return 0;
}
0
carly31 Messages postés 57 Date d'inscription mercredi 19 novembre 2008 Statut Membre Dernière intervention 16 janvier 2010 5
9 déc. 2009 à 16:58
C'est quoi cette horreur ?!!!!
C'est quoi ces fgetc sans aucune utilité ?!!!!

Un conseil, lire le K&R pour apprendre le C, car là, c'est grave...
0
Le code ci-dessus peut-etre une base, même si en l'état c'est une horreur. Utilise une regex, un test de pointeur d'octet comme condition de sortie de lecture/écriture et ne crée pas de troisième fichier inutile.
0
Cephei Messages postés 118 Date d'inscription mercredi 9 décembre 2009 Statut Membre Dernière intervention 10 décembre 2018 19
9 déc. 2009 à 19:04
Ha oui la c'est plus propre ! ^^
Bilow, pour bien programmer, il faut penser simplicité...
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
loupius Messages postés 697 Date d'inscription dimanche 1 novembre 2009 Statut Membre Dernière intervention 31 décembre 2017 148
9 déc. 2009 à 19:50
Simplicité, tu as raison. Toutefois il ne faut pas oublier que le 'C' est un langage de bas niveau ce qui implique, entre autres, la gestion des erreurs. Un programme plus correct serait:(mais l'essentiel a été bien fait par didji):
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
  char* nomFichierNonTraite = "fichier_non_traite.txt";
  char* nomFichierTraite = "fichier_traite.txt";
  FILE* ficNonTraite;
  FILE* ficTraite;
  char carac;

  if (!(ficNonTraite = fopen(nomFichierNonTraite, "r"))
  {
    printf("Erreur d'ouverture du fichier: %s\n", nomFichierNonTraite);
    return EXIT_FAILURE;
  }
  if (!(ficTraite = fopen(nomFichierTraite, "w"))
  {
    printf("Erreur d'ouverture du fichier: %s\n", nomFichierTraite);
    fclose(ficNonTraite);
    return EXIT_FAILURE;
  }
  while(!feof(ficNonTraite))
  {
    fread(&carac, sizeof(carac), 1, ficNonTraite);
    if(isupper(caract))
      fwrite(&carac, sizeof(carac), 1, ficTraite);
  }
  fclose(ficTraite);
  fclose(ficNonTraite);

  system("pause");
  return EXIT_SUCCESS;
}
Bonne soirée à tous.
0
kamit Messages postés 6 Date d'inscription mardi 16 juin 2009 Statut Membre Dernière intervention 16 décembre 2009
10 déc. 2009 à 10:40
Merci à tous.
0
kamit Messages postés 6 Date d'inscription mardi 16 juin 2009 Statut Membre Dernière intervention 16 décembre 2009
10 déc. 2009 à 11:46
Merci à tous. Cependant je dois le faire en C++. Voici ce que j´ai essayé.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <utility>


using namespace std;

struct Motiv {
vector<string> tokens; //enth䬴 unsere aminos䵲en
pair<int, int> Brackets; //der erste Element ist ein Zeichen, zweite die L䮧e der aminos䵲en
};

int main(){
vector<string>::iterator s;
/*// int klammer;
//int zahl_token;
Motiv dna_1, dna_2, dna_3;
dna_1.tokens[7] = ("G", "F", "R", "G", "AG", "L");
dna_1.Brackets = ((0,1), (0,1), (0,1), (0,1), (0,1), (2,2), (0,1));*/
Motiv dna;
//dna.tokens;
ifstream Datei("bact_Motives.txt", ios::in); //Datei lesen
ofstream File("C:protein.txt", ios::out);
if(Datei && File)
{
string inhalte;
int i = 0;

while(getline(Datei, inhalte))
{
File << inhalte << endl;
string::size_type found = inhalte.find_first_of("[]{}()-,");
while( found != string::npos) {
inhalte[found] =' ';
found = inhalte.find_first_of("[]{}()-,", found+1);
}
if(inhalte !="")
{
dna.tokens.push_back(inhalte);
}

}

for(s = dna.tokens.begin(); s != dna.tokens.end(); s++)
{
//if((*s == "[")|| (*s == "]") || (*s == "{") || (*s == "}") || (*s == "-" )|| (*s >= "1" && *s <= "9") || (*s == "(" ) || (*s == ")")){

//}
//s = s.replace("[", "");
cout << *s << endl;
}


Datei.close();
File.close();
}
else
cerr << "Datei konnte nicht gelesen werden" << endl;

system("pause");

return 0;
}

le probleme est maintenant le suivant: Quelle fonction permait d´annuller un caractere sans le remplacer?
0
Bonjour,

Je ne connaissais pas d'autre méthode que l'horreur que j'ai écrit, mais bon ca fonctionnait qd même non ?

Allé au revoir tout le monde.
0
kamit Messages postés 6 Date d'inscription mardi 16 juin 2009 Statut Membre Dernière intervention 16 décembre 2009
16 déc. 2009 à 02:13
s´lut les forumistes.
Le probleme m´a encore ete reposé sous la forme suivante:
On a un fichier, qui contient les Motifs de proteins suivants:
>PS00058
G-F-R-G-E-[AG]-L

>PS00059
G-H-E-x-{EL}-G-{AP}-x(4)-[GA]-x(2)-[IVSAC]

Le devoir est reecrire le contenu du fichier sous la forme suivante:
>PS00058
GFRGEAGL
>PS00059
GHEXELGXGAXIVSAC

Donc on doit annuler :[,],{,},(,),-
tout element annuler doit etre ecrit dans un fichier sous la forme (1, 2) pour[AG] par exemple ou (2,2) pour {AP}. En fait : 1 represente [; 2 represente {; 3---->(, 4-----> - et 0 si aucun des symboles n´est present.

Les chiffres prensents dans le string doivent tout simplement etre annulé.

J´ai pu developper ceci, mais ca ne marche.
Pouvez vous m´aider?

/*****************BEGIN*******************************************/
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <utility>


using namespace std;

struct Motiv {
vector<string> tokens; //content the amino acid
vector<pair<int, int> > brackets; //information about the brackets and the length of the charater
} Prot;
/**
* This function deletes all form of brackets in the string
* @param str is our string
* @param &vect is of typ vector<string> an has the character
*/

void strSplit(string str, vector<string> &vect)
{
int cutAt;
while( (cutAt = str.find_first_of("[]{}()-")) != str.npos )
{
if(cutAt > 0) vect.push_back(str.substr(0,cutAt));
str = str.substr(cutAt+1);
}
if(str.length() > 0) vect.push_back(str);
}

/****** end of function strSplit()***********************************/


/**
* This prints the brackets
* @param out
* @param charac
* @param brac the information about the bracket
*/


void printMBrackets(vector<pair<int, int> > brac, char charac, ostream &out)
{
int j = 0; //position of brackets
int i=0; // the length of one token
// vector<pair<int, int> > brac = make_pair(0,0);
if (charac == '[' || charac == '-' || charac == '{' || charac == '(' )
{
i++; // i = i+1
brac[j].second = i;
i = 0;
}
// if the founded charater is "[" we have 1, "{"--->2; "("--->3; "-" ----->4, else 0
switch (charac)
{
case '[':
brac[j].first = 1;
break;
case '{':
brac[j].first = 2;
break;
case '(':
brac[j].first = 3;
break;
case '-':
brac[j].first = 4;
break;
default:
brac[j].first = 0;
}

// brac.push_back(pair<int, int>(brac[j].first, brac[j].second));
out<<"("<<brac[j].first<<","<<brac[j].second<<")"<< endl; //
j++;
}

/*************end of printMBrackets()***********************************************/



/**
* This prints the Tokens
* @param out
* @param vect the information about the bracket
*/

void printMTokens(vector<string> vect, ostream &out)
{
for(vector<string>::iterator it = vect.begin(); it!=vect.end(); out<<*it<<" ", it++ );
out<<endl;
}

/***********************end of printMTokens()****************************************/

/**
* This prints the brackets
* @param f_name
*/

void readSeqFile(char* f_name)
{

/***** we try to delete all presented number in the string******************/
if (f_name)
{
f_name = strtok(NULL, "0123456789"); // delete 0,1,2,3,4,5,6,7,8,9
}

ifstream testIn(f_name); //open reading the the file testIn
string fres(f_name); //put f_name inside a string fres
fres += "Res";
ofstream testRes(fres.c_str()); //open writting the file testRes
if (testIn.is_open()) //check if the file is open
{
string line;
while (!testIn.eof() )
{
getline(testIn,line); //write the line in testIn
char c;
if ( line.empty() || (c = line.at(0)) == ' ') continue; //check if the line is empty or if it beginning whit a space
if ( c == '>')
{
Prot.tokens.push_back(line); //we get the name of the protein
getline(testIn,line); //amino acid
}

printMBrackets(Prot.brackets,c, testRes);
strSplit(line,Prot.tokens);
printMTokens(Prot.tokens, testRes);
Prot.tokens.clear();
Prot.brackets.clear();
}

testIn.close();
testRes.close();
}
else cout << "Unable to open in_file";
}

int main(int argc, char* argv[]){

readSeqFile(argv[1]);
system("pause");

return 0;
}
0