dimanche 1 mars 2015

How to cut or truncate a char in c

I am reading from a file of which each line is greater than 63 characters and I want the characters to be truncated at 63. However, it fails to truncate the lines read from the file.


In this program we are assuming that the file has 10 lines


Goal: I want to read 63 characters from each line. Any line that has more than 63 characters, 63 characters are read and the rest are truncated. If there is an easier way to do this please let me know.



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

int main(void)
{
char a[10][63];
char line[255];

int count = 0;

//Open file
FILE *fp;
fp = fopen("lines.dat", "r");

//Read each line from file to the "line array"
while(fgets(line, 255,fp) != NULL)
{
line[63] = '\0';

//copy the lines into "a array" char by char
int x;
for(x = 0; x < 64; ++x)
{
a[count][x] = line[x];
}

count++;
}

fclose(fp);

//Print all lines that have been copied to the "a array"
int i;
for(i = 0; i < 10; i++)
{
printf("%s", a[i]);
}


}

Aucun commentaire:

Enregistrer un commentaire