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 : 12/11/2008 22:30:04
Vue : 1684
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



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()
  }

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



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

{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} TESTS DE TRIS (WIN32)
En répose à la source: http://www.cppfrance.com/code.aspx?ID=48702 NON et NON !!! CombSort() es...

{Visual Basic, VB6, VB.NET, VB 2005} BLOQUER/DEBLOQUER UN FICHIER NTFS
Bonjour, Voici une toute petite source pour vous montrer comment bloquer/debloquer un fichier dan...

{} [FLEX 4/AIR] NOTEPAD DE BASE
Bonjour, Vous trouverez dans ce code les base d'un notepad classique. Toutes les fonctionnalités ...

{C / C++ / C++.NET} TXT SUPPRIMER LIGNES DOUBLONS (WIN32)
Demo pour cette question du forum: http://www.cppfrance.com/forum.v2.aspx?ID=1234830 Exe qui sup...

{C / C++ / C++.NET} LISTER LES FICHIERS D'UN REPERTOIRE + FILTRES
Programmé sous Linux. Compatible windows. Liste les fichiers d'un répertoire come indiqué dans le...

{C / C++ / C++.NET} PROTEGER UN DOSSIER ET LES FICHIER A L INTERIEUR
protégé un dossier et les fichier intérieur en renommant le dossier sous le nom de, au hasard ...