Les Snippets

Connexion

Récupérer une partie d'un fichier (ligne n à x)

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 06/11/2008 17:16:46 et initié par PCPT [Liste]
Date de mise à jour : 19/03/2009 19:33:23
Vue : 9687
Catégorie(s) : Fichier / Disque, Chaîne de caractères
Langages dispo pour ce code :
- VB6, VBA
- VB 2005
- Delphi 5
- VB 2005, VB 2008, VB.NET 1.x
- C# 1.x, C# 2.x, C# 3.x
- PHP 4, PHP 5



Langage : VB6 , VBA
Date ajout : 06/11/2008
Posté par PCPT [Liste]
DateMAJ : 06/11/2008
Public Function GetFilePart(ByVal sPath As String, ByVal lLineStart As Long, ByVal lLineStop As Long) As String
'sPath      -> chemin, fichier DOIT exister
'lLineStart -> ligne de départ, commence à 1
'lLineStop  -> ligne de fin,  peut être supérieur au nombre  total
'lLineStart et lLineStop doivent être  logiques, pas de la ligne 8 à 5 par exemple
    Dim FF        As Integer
    Dim asLines() As String
    Dim sLine     As String
    Dim i         As Long
    FF = FreeFile
    i = 0
    ReDim asLines(lLineStart To lLineStop)
    Open sPath For Input As #FF
        Do While Not EOF(FF)
            i = i + 1
            Line Input #1, sLine
            If (i >= lLineStart) And (i <= lLineStop) Then
'               numéro ligne en  cours est dans la plage, on conserve
                asLines(i) = sLine
            ElseIf i > lLineStop Then
'               dernière lignes  "voulue" lue, pas besoin de parcourir le reste
                Exit Do
            End If
        Loop
    Close #FF
'    dépassement?
    If lLineStop > i Then ReDim Preserve  asLines(lLineStart To  i)
    
'    retour
    GetFilePart = Join(asLines, vbCrLf)
    Erase asLines
End Function
'
' ---------------------
' EXEMPLE  D'UTILISATION
'   on considère un fichier  contenant 20 lignes
'  ---------------------
Private Sub Exemple()
'   retourne  tout
    MsgBox GetFilePart("c:\mon_fichier.txt"166)
'   retourne les 5 dernières lignes
    MsgBox GetFilePart("c:\mon_fichier.txt"1520)
    MsgBox GetFilePart("c:\mon_fichier.txt"15300)
'   retourne 5 lignes, depuis la l0ème
    MsgBox GetFilePart("c:\mon_fichier.txt"1015)
End Sub

Remarque :
pour savoir combien de lignes votre fichier contient, voir ici :
http://www.codyx.org/snippet_compter-nombre-lignes-fichier_729.aspx#2152
Langage : VB 2005
Date ajout : 07/11/2008
Posté par jrivet [Liste]
Public Function GetFilePart(ByVal sPath As String, ByVal lLineStart As Long, ByVal lLineStop As Long) As String    Dim FReader As StreamReader    Dim Res As String = String.Empty    Dim Ret As String = String.Empty    Dim Count As Integer = 0    'La encore comme dans le snippet de PCPT,    'lLineStart et lLineStop doivent être  logiques, pas de la ligne 8 à 5 par exemple    'On vérifie l'existence du fichier    If File.Exists(sPath) Then        'ouverture du fichier        FReader = New StreamReader(sPath, System.Text.Encoding.GetEncoding("iso-8859-1"))        'tant que nous ne somme pas à la ligne        'souhaitée        While Count < (lLineStart - 1)            Call FReader.ReadLine            Count += 1        End While        While Count < lLineStop            'on vérifie de ne pas être arrivé à la fin            'du flux            If Not FReader.EndOfStream Then                'on lit la ligne                Ret = FReader.ReadLine                'on concatène avec le résultat                Res = String.Concat(Res, Ret, Environment.NewLine)                Count += 1            Else                Exit While            End If        End While    End If    Return Res End Function
By Renfield
Remarque :
Salut, petite version .NET.
A utiliser de la même façon que le snipper de PCPT. A l'exception près que celui si vérifie l'existence du fichier.
Langage : Delphi 5
Date ajout : 11/11/2008
Posté par f0xi [Liste]
procedure GetFileLines(const FileName: string; const LineStart, LineEnd: integer; Output: TStrings);
var N, St, En, CpC: integer;
    Input: TStringList;
begin
  Output.BeginUpdate;
  try
    Input := TStringList.Create;
    try
      Input.LoadFromFile(FileName);
      St := LineStart;
      En := LineEnd;
      if St < 0 then
        St := 0;
      if En > (Input.Count-1) then
        En := Input.Count-1;
      Cpc := En-St;
      if Cpc = (Input.Count-1) then
        Output.Assign(Input)
      else
        for N := St to En do
          Output.Add(Input[N]);
    finally
      Input.Free;
    end;
  finally
    Output.EndUpdate;
  end;
end;
Langage : VB.NET 1.x , VB 2005 , VB 2008
Date ajout : 12/11/2008
Posté par Willi [Liste]
Public Function GetPartOfTextFile(ByVal path As String, ByVal StartMarkerLine As UInteger, ByVal EndMarkerLine As UInteger) As String 
 
        Dim szbTemp As New System.Text.StringBuilder 
 
        If StartMarkerLine > EndMarkerLine Then 
            Throw New Exception("Erreur dans les marqueurs de lignes début et/ou fin.") 
        End If 
 
        If System.IO.File.Exists(path) Then 
 
            Using fs As System.IO.FileStream = System.IO.File.OpenRead(path) 
                Using sr As New System.IO.StreamReader(fs) 
 
                    Dim uiMarker As UInteger = 0 
                    Dim sReadLine As String = String.Empty 
 
                    Do While sr.EndOfStream = False 
 
                        sReadLine = sr.ReadLine() 
                        uiMarker += 1 
 
                        If (StartMarkerLine <= uiMarker) AndAlso (EndMarkerLine >= uiMarker) Then 
                            szbTemp.AppendLine(sReadLine) 
                        ElseIf EndMarkerLine < uiMarker Then 
                            Exit Do 
                        End If 
 
                    Loop 
 
                End Using 
            End Using 
 
        Else 
            Throw New System.IO.IOException(String.Format("Le fichier {0} n'existe pas", path)) 
        End If 
 
        Return szbTemp.ToString() 
 
    End Function

Remarque :
Exemple:
Dim sTextpart as string= GetPartOfTextFile("C:\MonFichier.txt",3,10)
Langage : C# 1.x , C# 2.x , C# 3.x
Date ajout : 12/11/2008
Posté par Willi [Liste]
DateMAJ : 12/11/2008
public string GetPartOfTextFile(string path, uint StartMarkerLine, uint EndMarkerLine)
{
  System.Text.StringBuilder szbTemp = new System.Text.StringBuilder();
  if (StartMarkerLine > EndMarkerLine)
  {
    throw new Exception("Erreur dans les marqueurs de lignes début et/ou fin.");
  }
  if (System.IO.File.Exists(path))
  {
    using (System.IO.FileStream fs = System.IO.File.OpenRead(path)) {
      using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) {
        uint uiMarker = 0;
        string sReadLine = string.Empty;
        while (sr.EndOfStream == false) {
          sReadLine = sr.ReadLine();
          uiMarker += 1;
          if ((StartMarkerLine <= uiMarker) && (EndMarkerLine >= uiMarker))
          {
            szbTemp.AppendLine(sReadLine);
          }
         else if (EndMarkerLine < uiMarker) {
            break;
          }
        }
      }
    }
    return szbTemp.ToString()
  }
Langage : PHP 4 , PHP 5
Date ajout : 15/02/2009
Posté par wererabbit [Liste]
DateMAJ : 19/03/2009
/*
*@param string $file Chemin du fichier texte
*@param int $startLine Première ligne du texte que l'ont veut retourner. Le fichier commence à la ligne 0
*@param int $enLine Dernière ligne du texte que l'ont veut retourner
*@return string Une chaîne de caractère comprenant les lignes de $startLine à $endLine du fichier texte
*/
GetFilePart($file, $startLine, $endLine)
{
    if($endLine< 0) {
          return false;
      }
    $return = '';
    $files = file($file);
    if($startLine < 0) {
        $startLine = 0;
    }
    $iCpt = count($file);
    if($iCpt < $endLine) {
        $endLine = $iCpt;
    }
    for($i = $startLine; $i <= $endLine; $i++)
    {
        //if($i < count($files) && $i >= 0)
            $return .= $files[$i];
    }
    
    return $return;
}
//Exemple : 
//retourne les 10 premières lignes du fichier
$text = GetFilePart('file.txt',  0, 10);
Remarque :
Correction et optimisation par Malalam : inutile d'appeler le count() DANS la boucle, il sera alors exécuté autant de fois qu'on boucle alors que le nombre de lignes contenues dans le fichier ne bouge pas.
Si $endLine est négatif, on renvoie false, ça ne tient pas debout d'avoir un entier négatif ici (où on balance une exception). Si $startLine est négatif, on le fixe à 0 histoire d'essayer quand même.
Sinon, on peut utiliser array_splice(), plus simplement, mais moins performant qu'une boucle.

Snippets en rapport avec : Fichier, Lignes, Récupérer, Partie, Écart



Codes sources en rapport avec : Fichier, Lignes, Récupérer, Partie, Écart

{PHP} RÉCUPÉRER LE TYPE D'UN FICHIER (3 FONCTIONS DIFFÉRENTES)
Bonjour à tous, La plupart des gens pense que récupérer l'extension d'un fichier envoyé par form...

{Python} FONCTION COMPTER LE NOMBRE DE LIGNE
Bonjour, ma première fonction que je poste ... Pour les gros débutant (dont je fais parti) je pense ...

{Visual Basic, VB6, VB.NET, VB 2005} GETNAMES : RÉCUPÈRE ET ÉCRIT TOUS LES NOMS DE FICHIERS D'UN DOSSIER
J'ai fait ce petit programme tout simple, qui aurait pu être créé par n'importe quel débutant, car j...

{C / C++ / C++.NET} NOMBRE DE LIGNES ET DE COLONNES D'UN FICHIER
Voici ma première source, qui permet de trouver le nombre de colonnes et de lignes d'un fichier avec...

{Visual Basic, VB6, VB.NET, VB 2005} NTFS RECOVER : RÉCUPÉRER LES FICHIERS EFFACÉS D'UNE PARTITION NTFS
Ce code permet de récupérer les fichiers effacés de vos partitions NTFS. Pour cela, vous devez avoir...

{Visual Basic, VB6, VB.NET, VB 2005} SCRIPT EN VBS QUI DÉCOUPE UN FICHIER EN PLUSIEURS FICHIERS DE X LIGNES.
Ce script permet de découper un fichier en plusieurs fichiers de x lignes. Je l'utilise assez souve...

{C / C++ / C++.NET} EDITER UN FICHIER BIT PAR BIT
Bonjout, J'ai récemment eu besoin d'éditer un fichier bit à bit mais ne trouvant pas de moyen de ...

{PHP} CHARGER DES DONNÉES DEPUIS UN FICHIER TXT DANS UNE BASE DE DONNÉE
le titre dit tout dejàs ce script utilise une base de données Mysql les requêtes pour la création ...

{Visual Basic, VB6, VB.NET, VB 2005} INSERER TOUT TYPE DE FICHIERS DANS ORACLE EN VB.NET
Ce petit code permet d'ajouter tout type de fichiers dans oracle et par la suite de les récupérer, l...

{C / C++ / C++.NET} FICHIER ALBUM MUSICAL
.............................................................................creer un fichier conten...