0

I use the fgets function to read and if the queue is shorter than the maximum length of the sor, the function will also read the line break, which could result in an erroneous result.

My code is working well, but when the tester test my program it is fail every time because of the line break which is working, but it is not working for my first lien of the output. How can I solve this problem?

#ifndef UTILS_H 
#define UTILS_H 
void fordit();
#endif
#include <stdio.h>
#include "beadando2.h"

int main(int argc, char *argv[]) {
    FILE *fp;
    if (argc == 1){
        fordit( stdin, "stdin");
    } else if (argc == 0){
        printf(" ");
    }
     else{
        for(int a=1; a<argc; a++){
        fp = fopen(argv[a],"r");
        if (fp !=0 ){
        fordit(fp,argv[a]); 
        fclose(fp);
        }   else {
        fprintf(stderr,"%s\n","File opening unsuccessful !"); 
        }
    }
    }

}
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include "beadando2.h"

void kiir(char **osszsor, int dbsor);
void sorforditva(char *egysor);
void memoria(void *ptr);
void fordit(FILE *fp);


char **beolvas(FILE *fp, int *sorok){
  int tombmeret = 8;   
  char sor[1024]; 

  char **beolvsorok = (char **)malloc(tombmeret * sizeof(char*));  
  int dbsor = 0;   
  memoria(beolvsorok);
  while (fgets(sor, 1024, fp) !=0  )
  {
    int hossz = strlen(sor);    
    while (hossz && ('\n'== sor[hossz-1] || '\r'== sor[hossz-1]) ) 
    {
       sor[--hossz] ='\0';     
    }
    while (dbsor == tombmeret)   
    {
      tombmeret = tombmeret*2;       
      beolvsorok = realloc(beolvsorok, tombmeret* sizeof(char *));
      memoria(beolvsorok);
    }
    beolvsorok[dbsor] = (char *) malloc(hossz++);    
    memoria(beolvsorok[dbsor]);
    strcpy(beolvsorok[dbsor],sor);     
    dbsor++;
  }
  *sorok = dbsor;  
  return beolvsorok;
}

void fordit(FILE *fp)
{
  int dbsor = 0;
  char **osszsor = beolvas( fp, &dbsor);    
  kiir(osszsor, dbsor); 
}

void sorforditva(char *egysor)
{
  int len = strlen(egysor);   
  while (-1<len--){
    fputc(egysor[len],stdout);      
  } fputc('\n',stdout);
}

void kiir(char **osszsor,int dbsor)
{
  for (int i = dbsor-1; -1< i; i--)  {
    char *jelenlegi = osszsor[i];
    fprintf(stdout,"%d ",i+1);
    sorforditva(jelenlegi); 
    free(jelenlegi);
  }
  free(osszsor);
}

void memoria(void *ptr)
{
  if ( 0 == ptr ){
    fprintf(stderr,"Memory allocation failed!\n");
    exit(1);    
  }   
}
batat
  • 29
  • 5
  • It is in the manual. If the input to `fgets` has less than the stated size, `1024` in your case, a `\n` is kept at the end. So you just need to reverse that: if the input has less than `1024` just replace the last byte by `0`. – arfneto Nov 28 '21 at 21:35

0 Answers0