End of File occurs when reading char 0x1A - c

I am trying to read a file with around 1000 characters in it. The file reading terminates when an 0x1A character is encountered. I want that:
0x1A should not terminate the reading.
0x1A should be stored like a normal character.
Can I use an alternate method of reading the file, maybe?
int main(void)
{
int x=0,ch = ' ', file_name[25], arr[1000];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); getchar();
int y= 0;
while ((ch = fgetc(fp)) != EOF)
{
printf("%d) %x \n",y, ch);
arr[y++] = ch;
printf(" %x \n", arr[(y- 1)]);
}
printf("Press to see the data off array..."); getchar();
for (int x = 0; x < y; x++)
{
printf("%d ", (x + 1));
printf(". %x \n", arr[x]);
}
getchar();
fclose(fp);
return(0);
}

You opened the file as txt mode,
fp = fopen(file_name, "r"); // txt mode
Please try binary mode to read 0x1A,like
fp = fopen(file_name, "rb"); // binary mode

Instead of fgetc() you can use fgets .
while ((ch = fgetc(fp)) != EOF)
{
printf("%d) %x \n",y, ch);
payload[y++] = ch;
printf(" %x \n", arr[(y- 1)]);
}
you can simply write this using fgets()-
#define MAX 1024
//open file in "r" mode
char arr[MAX];
while(fgets(arr,MAX,fp))
{
printf("%s",arr);
}
Content in you file is stored in array arr.
While using fgets you don't have to worry about EOF as fgets itself return as it encounters EOF.

Related

fprintf places in odd value when processing char value

I am writing what should be a simple program, but I'm having an odd issue with fprintf I have not been able to solve.
I am reading a small CSV text file and writing those values to a separate file containing only the numeric values.
My CSV file looks like this.
000,001,002,
003,004,005,
006,007,008,
009,010,011,
255,255,255
There is a comma between each value and a return at the end of each line.
The code I am using is
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
FILE * inputFile;
FILE * outFile;
char * filename;
int records = 0;
char line[15];
char * sp;
char appendString[] = ".hex";
printf("useage: dec2hex inputFile.txt\n");
// Check if a filename has been specified in the command
if (argc < 2) {
printf("Missing Filename\n");
return (1);
} else {
filename = argv[1];
printf("Read in Filename : %s\n", filename);
}
// Open file in read-only mode
inputFile = fopen(filename, "r");
if (inputFile == NULL) {
printf("Hey! Failed to open the file\n");
return (1);
}
strcat(filename, appendString);
printf("write out filename : %s\n", filename);
outFile = fopen(filename, "w");
while (fgets(line, 15, inputFile) != NULL) {
sp = strtok(line, ",");
char Y_pos = atoi(sp);
sp = strtok(NULL, ",");
char X_pos = atoi(sp);
sp = strtok(NULL, ",");
char OType = atoi(sp);
//print to file
fprintf(outFile, "%c", Y_pos);
fprintf(outFile, "%c", X_pos);
fprintf(outFile, "%c", OType);
records++;
}
fprintf(outFile, '\0');
printf("records = %d\n", records);
fclose(inputFile);
fclose(outFile);
return (0);
}
This will write to a file ..hex
The output I'm expecting should be
000102030405060708090a0bffffff
However what I'm seeing is an odd value inserted $D0.
I'm expecting $0A which does happen afterwards. I have tried some other values in my CSV (from 0 to 50) and this for now seems to be the only value that is random.
The reason I'm using %c in my fprintf is that I only need values from 0-255.
My first question, is why the odd value when processing 010?
How can this be corrected?
I'm using the TCC compiler 0.9.26, but have gotten similar results when using VS.
Thanks
However what I'm seeing is an odd value inserted $D0 $0D.
File was opening in text mode and when writing a code 10 ('\n'), incurred a "\n" to "\r\n" translation on OP's machine.
Instead open the file in binary mode.
// outFile = fopen(filename, "w");
outFile = fopen(filename, "wb");
Note: Other code short-comings exist.
you do not this strtok and atoi magic or binary mode opening magic
int main(void)
{
char line[1000];
while (fgets(line, 100, stdin) != NULL)
{
int X,Y,O;
if(sscanf(line, "%d,%d,%d,", &Y, &X, &O) != 3) { /* error handling*/ }
else
{
printf("%02x ", Y);
printf("%02x ", X);
printf("%02x ", O);
}
}
}
https://godbolt.org/z/vvKGzdcvd

C Input value from .txt to struct

I need to scan values from .txt to a structure so I can work further on with my program. I've been trying various methods from the thread and this is the closes I got to a successful build.
I can NOT get the values to be printed out so I can test if they scanned correctly before working my way further into the program.
I have different values in struct:
struct knyga
{
char vardas[10];
char pavadinimas[50];
int metai;
double kaina;
};
and this is my reading function:
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius;
int txt;
txt = fgetc(fp);
while((txt = fgetc(fp)) != EOF){
if(txt == '\n') skaicius++;
txt = fgetc(fp);
}
printf("%d", skaicius);
fp = fopen("duomenys.txt", "r");
for(int i = 0; i < skaicius; i++){
fscanf(fp, "%s %s %d %lf", arr_knyga[i].vardas, arr_knyga[i].pavadinimas, &arr_knyga[i].metai, &arr_knyga[i].kaina);
}
fclose(fp);
}
EDIT:
This is the content of my text file:
Onute Knyga 1999 12.12
Petras Knygute 2001 9.99
EDIT 2:
my main function:
int main() {
struct knyga arr_knyga[10];
Skaitymas(arr_knyga);
return 0;
}
You call txt = fgetc(fp); too often. The two occurrences of this line must be removed.
Especially in the loop you have one call to fgetc that is checked for '\n' and a second call that is not checked, so there is a 50%/50% chance that a '\n' is not counted.
You forgot to initialize the counter variable.
The counting would be correct with this version:
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius = 0;
int txt;
while((txt = fgetc(fp)) != EOF){
if(txt == '\n') skaicius++;
}
printf("%d", skaicius);
fclose(fp);
}
But it would be better to omit the line-counting and detect the end-of-file condition in the fscanf loop.
void Skaitymas(struct knyga arr_knyga[]){
FILE *fp;
fp = fopen("duomenys.txt", "r");
int skaicius = 0;
int rc;
while(1)
{
rc = fscanf(fp, "%s %s %d %lf", arr_knyga[skaicius].vardas, arr_knyga[skaicius].pavadinimas, &arr_knyga[skaicius].metai, &arr_knyga[skaicius].kaina);
if(rc == 4)
{
skaicius++;
}
else
{
break;
}
}
if(!feof(fp))
{
fprintf(stderr, "error reading file or wrong data after line %d\n", skaicius);
}
else
{
printf("%d", skaicius);
}
fclose(fp);
}

How to read a file into an array of structs?

Im trying to read a text file into an array of structs, but when trying to print the array, the struct is empty. The printing function works fine and I think the problem is in getRawData.
struct student
{
char ID[MAXID + 1];
char f_name[FIRST_NAME_LENGTH + 1];
char s_name[LAST_NAME_LENGTH + 1];
int points[MAXROUNDS];
};
//main//
case 'W':
if(save(array, len) == 0);
{
printf("Data saved.\n");
}
break;
case 'O':
if(getRawData(array, len));
{
printf("File read.\n");
}
break;
int save(struct student *h, int num_students)
{
char name[20];
printf("Enter file name: " );
scanf("%s", name); // Read in filename
FILE *output = fopen(name, "w"); // open the file to write
if (!output) {
return -1; // error
}
for (int i = 0; i < num_students; ++i)
{
fprintf(output, "%s %s %s \n", h[i].f_name, h[i].s_name, h[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fprintf(output, "%d\n", h[i].points[j]);
}
printf("Information of student %s %s (%s) written into file %s\n", h[i].s_name, h[i].f_name, h[i].ID, name);
}
fclose(output); // close
return 0;
}
int getRawData(struct student *records)
{
int i;
int nmemb; // amount of structs
char name[20];
printf("Name of the file to be opened: \n");
scanf("%s", name);
FILE *outtput = fopen(name, "r");
int ch=0;
int lines=0;
if (outtput == NULL);
return 0;
lines++;
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
{
lines++;
}
}
nmemb = lines / 7;
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
for(int j = 0; j < MAXROUNDS; j++)
{
fscanf(outtput, "%d\n", &records[i].points[j]);
}
}
printf("%d", lines);
return i;
}
So my goal is to get the data from the file and write it over whatever there is stored in the struct array. I would appreciate some help as I have been working on this for way too long.
Look at this code in getRawData(), first you are reading file to identify total number of lines:
while(!feof(outtput))
{
ch = fgetc(outtput);
if(ch == '\n')
.....
.....
due to this the file stream pointer pointing to EOF and after this, in the for loop, you are doing:
for(i = 0; i < nmemb; i++) {
fscanf(outtput, "%s %s %s", records[i].f_name, records[i].s_name, records[i].ID);
.....
.....
Here, the fscanf() must be returning the EOF because there is nothing remain to read from stream file. You should check the return value of fscanf() while reading file.
You should reset the pointer to start of file before reading it again. You can use either rewind(ptr) or fseek(fptr, 0, SEEK_SET). Below is a sample program to show you what is happening in your code and how the solution works:
#include <stdio.h>
int main (void) {
int ch;
int lines = 0;
char str[100];
FILE *fptr = fopen ("file.txt", "r");
if (fptr == NULL) {
fprintf (stderr, "Failed to open file");
return -1;
}
while (!feof(fptr)) {
ch = fgetc (fptr);
if(ch == '\n') {
lines++;
}
}
printf ("Number of lines in file: %d\n", lines);
printf ("ch : %d\n", ch);
printf ("Now try to read file using fscanf()\n");
ch = fscanf (fptr, "%s", str);
printf ("fscanf() return value, ch : %d\n", ch);
printf ("Resetting the file pointer to the start of file\n");
rewind (fptr); // This will reset the pointer to the start of file
printf ("Reading file..\n");
while ((ch = fscanf (fptr, "%s", str)) == 1) {
printf ("%s", str);
}
printf ("\nch : %d\n", ch);
fclose (fptr);
return 0;
}
The content of file reading in the above program:
Hello Vilho..
How are you!
Output:
Number of lines in file: 2
ch : -1
Now try to read file using fscanf()
fscanf() return value, ch : -1
Resetting the file pointer to the start of file
Reading file..
HelloVilho..Howareyou!
ch : -1
Here you can see, the first ch : -1 indicate that the file pointer is at EOF and if you try to read you will get EOF because there is nothing left to read. After resetting file pointer, you can see fscanf() is able to read file.
You should not use while (!feof(file)). Check this.

print the first letter of a file in C

Hello guys I am having a problem in printing the first two letter/characters of a .txt file which contains --> "need help". I would like to print the first two letters --> "ne". I tried with ch[], but I couldnt fix, so i changed it back to the part which works:
int main() {
char ch, file_name[2];
int i;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r");
if( fp == NULL )
{
printf("Error while opening the file.\n");
exit(1);
}
printf("The contents of %s file are :\n", file_name);
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}
int main() {
char ch[2];
FILE *fp;
fp = fopen("file.txt","r");
fread(ch,2,1,fp);
printf("(%c%c) (%2.2s)",ch[0], ch[1],ch);
}
stdout :
(ne) (ne)
I don't know why you need only the two first letters, but here's how to do it.
char file_name[256];
gets(file_name);
int lenght = 0;
strlen(file_name) > 2 ? lenght = 2: lenght = strlen(file_name);
for(int i = 0; i < lenght; i++)
printf("%c", file_name[i]);
But an advice that I can give you for strings in C (char arrays) is try to always create a bigger array that you need. It doesn't cost much memory and it's always safer to have more than enough. When you call standards functions like printf(), they will check the null terminated character and this will defines the size of your string.
This is what i came up so far. It prints the first two characters, but then it prints questions marks within a square underneath.
Here is the code:
int main() {
char ch[2], file_name[100];
int i;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name,"r");
if( fp == NULL )
{
printf("Error while opening the file.\n");
exit(1);
}
printf("The contents of %s file are :\n", file_name);
fscanf(fp, "%2s", ch);
printf("%s\n", ch);
while( ( ch[i] = fgetc(fp) ) != EOF ){
printf("%c",ch);
}
fclose(fp);
return 0;
}

Write to .txt file?

How can I write a little piece of text into a .txt file?
I've been Googling for over 3-4 hours, but can't find out how to do it.
fwrite(); has so many arguments, and I don't know how to use it.
What's the easiest function to use when you only want to write a name and a few numbers to a .txt file?
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf("\nNew contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c\n[ %d ]\n\n", name, number);
fclose(f);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);
/* printing single characters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

Resources