I have a text file that has a structure like:
P2
# CREATOR: GIMP PNM Filter Version 1.1
445 243
255
108
107
104
102
102
[...]
And i want to read this text file line by line. So i writed this code:
int main(void) {
char str[50];
FILE *fp;
fp = fopen("/home/user/Downloads/file.pgm", "r");
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fgets() function: \n\n");
printf("Reading contents of myfile.txt: \n\n");
while( fgets(str, 30, fp) != NULL )
{
puts(str);
}
fclose(fp);
return 0;
}
However, it gives a strange output. And i don't know where is the error. The code seems ok. What do you think ?
Execution :
You're limiting the fgets to 30 chars, and the comment
# CREATOR: GIMP PNM Filter Version 1.1
is 38 characters.
it is simple fgets also return the \n when it is read (it is not discarded) and writing by puts you add an other \n after the print, so you have 2 \n creating an empty line
Replace puts(str); by fputs(stdout, str); and you will not have the empty lines
Note : the output doesn't correspond to the beginning of the file, may be its end ?
if I put
P2
# CREATOR: GIMP PNM Filter Version 1.1
445 243
255
108
107
104
102
102
in the file the execution gives :
pi#raspberrypi:/tmp $ ./a.out
Testing fgets() function:
Reading contents of myfile.txt:
P2
# CREATOR: GIMP PNM Filter Ve
rsion 1.1
445 243
255
108
107
104
102
102
one line is cut because has more than 29 characters
Related
I have a text file, where each line is an integer with a newline character. I also have a .bin file with the same thing.
10
20
30
40
50
60
70
Running this code...
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int input;
FILE *infile_t = fopen("numbers.txt", "r");
FILE *infile_b = fopen("numbers.bin", "rb");
if (infile_t == NULL) {
printf("Error: unable to open file %s\n", "numbers.txt");
exit(1);
}
if (infile_b == NULL) {
printf("Error: unable to open file %s\n", "numbers.bin");
exit(1);
}
printf("Enter an integer index: ");
while(scanf("%d",&input) != EOF){
int ch;
fseek(infile_t, (input*sizeof(int))-1, SEEK_SET);
fscanf(infile_t, "In text file: %d\n", &ch);
printf("In text file: %d\n", ch);
fseek(infile_b, (input*sizeof(int))-1, SEEK_SET);
fscanf(infile_b, "%d\n", &ch);
printf("In binary file: %d\n", ch);
printf("Enter an integer index: ");
}
fclose(infile_t);
fclose(infile_b);
return 0;
}
and entering 0, 1, 2, 3, 4 consecutively, I get the outputs:
10
0
40
50
0
I am trying to read the file by 4 bytes at a time (each int) and print the integer. What am I doing wrong and if this is bad practice, what would be better?
There is a difference between the textual representation of numbers and their binary representation.
Your input is a text file, which is a sequence of characters:
"10lf20lf30lf40lf50lf60lf70lf"
Its size is 21 bytes, which you could check with your file explorer.
And as bytes in a tabular form it looks like this, assumed that you are using ASCII and a unix-like system:
Offset
Bytes
Text
0
31 30 0A
"10lf"
3
32 30 0A
"20lf"
6
33 30 0A
"30lf"
9
34 30 0A
"40lf"
12
35 30 0A
"50lf"
15
36 30 0A
"60lf"
18
37 30 0A
"70lf"
There are no integers stored in binary form in your input file.
The function fseek() places the "cursor" into the file at the specified offset.
Then you call scanf() to scan and interpret(!) the sequence of characters that start at that offset.
Input
Offset set by fseek()
Text
Resulting value
0
0
"10lf..."
10
1
4
"0lf..."
0
2
8
"lf40lf..."
40
3
12
"50lf..."
50
4
16
"0lf..."
0
Since scanf() skips leading whitespace, you get "40" in the third case.
You cannot use fseek() in the general case to "jump" to a certain line in a text file. Except, that you know how long each line is. In your case this is known, and if you use a factor of 3 instead of 4, you will get what you seem to want.
I don't know what is in your 'numbers.bin', and you opened 'numbers.txt' as infile_t but didn't use it.
Assuming that the content in 'numbers.bin' is the text content in your question, and you open it in binary mode for reading, the contents stored in the file are as follows(end with one byte '\n' instead of two bytes '\r\n'):
\x31\x30\x0a\x32\x30\x0a\x33\x30\x0a\x34\x30\x0a\x35\x30\x0a\x36\x30\x0a\x37\x30
At this time, the file pointer is at the head of the file, pointing to the text content '1'(ascii code is 0x31).
\x31\x30\x0a\x32\x30\x0a\x33\x30\x0a\x34\x30\x0a\x35\x30\x0a\x36\x30\x0a\x37\x30
↑
when you use scanf("%d",&input) and input '0', the integer variable input will be 0, then you set the file pointer via fseek(infile_b, input*4, SEEK_SET), the file pointer will point to offset 0 relative to the beginning of the file.
Next line fscanf(infile_b, "%d\n", &ch) will read a integer value to variable ch, then ch will store the value 10 and print it to standard output (stdout) via printf.
When you enter '1', the file pointer will be set to 4, which will point to the fifth byte position relative to the beginning of the file, as follows:
\x31\x30\x0a\x32\x30\x0a\x33\x30\x0a\x34\x30\x0a\x35\x30\x0a\x36\x30\x0a\x37\x30
↑
The ascii code of the text value '0' is 0x30. It will read an integer value 0 and store it in ch.
You can replace fseek(infile_b, input*4, SEEK_SET) with fseek(infile_b, input*3, SEEK_SET), and will get the expected output.
I am trying to loop over stdin, but since we cannot know the length of stdin, I am not sure how to create the loop or what condition to use in it.
Basically my program will be piped in some data. Each line in the data contains 10 characters of data, followed by a line break (So 11 characters per line)
In pseudocode, what I am trying to accomplish is:
while stdin has data:
read 11 characters from stdin
save 10 of those characters in an array
run some code processing the data
endwhile
Each loop of the while loop rewrites the data into the same 10 bytes of data.
So far, I have figured out that
char temp[11];
read(0,temp,10);
temp[10]='\0';
printf("%s",temp);
will take the first 11 characters from stdin,and save it. The printf will later be replaced by more code that analyzes the data. But I don't know how to encapsulate this functionality in a loop that will process all my data from stdin.
I have tried
while(!feof(stdin)){
char temp[11];
read(0,temp,11);
temp[10]='\0';
printf("%s\n",temp);
}
but when this gets to the last line, it keeps repeatedly printing it out without terminating. Any guidance would be appreciated.
Since you mention line breaks, I assume your data is text. Here is one way, when you know the line lengths. fgets reads the newline too, but that is easily ignored. Instead of trying to use feof I simply check the return value from fgets.
#include <stdio.h>
int main(void) {
char str[16];
int i;
while(fgets(str, sizeof str, stdin) != NULL) { // reads newline too
i = 0;
while (str[i] >= ' ') { // shortcut to testing newline and nul
printf("%d ", str[i]); // print char value
i++;
}
printf ("\n");
str[i] = '\0'; // truncate the array
}
return 0;
}
Program session (ended by Ctrl-Z in Windows console, Ctrl-D in Linux)
qwertyuiop
113 119 101 114 116 121 117 105 111 112
asdfghjkl;
97 115 100 102 103 104 106 107 108 59
zxcvbnm,./
122 120 99 118 98 110 109 44 46 47
^Z
i want to decode an ASN.1 standard binary file. i have converted the binary file to hex and stored it in a file. now i want to convert this hex to ascii. The problem im having now is how to read the hex file.
the file looks this way,
81 01 32 82 0D 35 31 34 32 34 31 38 38 38 where 81 is a header, 01 is the size and 32 is the data. again 82 is the header and this goes on. how do i read from this file and differentiate between the various fields present.
i searched all over the internet for this, but couldnt get a satisfactory answer. so can someone help me with the way forward . i dont want any code, just want the procedure how i can do it.
I would first read the header and then in a loop the data. You can read hexadecimal numbers with the "x"-specifier (say your file is named hexfile.txt):
#include <stdio.h>
int main ()
{
FILE *stream;
unsigned int h, l, d;
if( (stream = fopen( "hexfile.txt", "r" )) == NULL ) return 1;
while (EOF != fscanf (stream, " %x %x", &h, &l))
{
printf ("%02X %02X\n",h,l);
for (unsigned i=0; i<l; ++i)
{
if (EOF == fscanf (stream, " %x", &d)) break;
printf ("%02X ",d);
}
puts ("");
}
fclose (stream);
return 0;
}
I'm working a program for a class and it's proving much more difficult than I thought.
It's my very first experience with C, but I've had some experience with Java so I understand the general concepts.
My goal: read in a text file that has some formatting requirements contained within the file, store the file in an array, apply the formatting and output the formatted text to stdout.
The problem: reading in the file is easy, but I'm having trouble with the formatting and output.
The challenge:
--the input file will begin with ?width X, ?mrgn Y, or both (where X and Y are integers). these will always appear at the beginning of the file, and will each be on a separate line.
--the output must have the text formatted as per the formatting request (width, margin).
--additionally, there is a 3rd format command, ?fmt on/off, which can appear multiple times at any point throughout the text and will turn formatting on/off.
--just a few catches: if no ?width command appears, formatting is considered off and any ?margin commands are ignored.
--if a ?width command appears, formatting is considered on.
--the files can contain whitespace (as both tabs and spaces) which must be eliminated, but only when formatting is on.
--dynamic memory allocation is not allowed.
Easy for a first C program right? My professor is such a sweety.
I've been working on this code for hours (yes, I know it doesn't look like it) and I'm making little progress so if you feel like a challenge I would very much appreciate help of any kind. Thanks!
So far my code reads in the text file and formats the margin correctly. Can't seem to find a good way to eliminate whitespace (I believe tokenizing is the way to go) or do the word wrap when the length of the line is longer than the ?width command.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #define MAX_LINE_LEN 133 /* max 132 char per line plus one extra for the new line char
6 #define MAX_LINES 300 /* max 300 lines per input file */
7 #define MAX_CHARS 39900 /* max number of characters in the file */
8
9 /* Initializes array used to store lines read in from text
10 file as well as output array */
11 char input[MAX_LINE_LEN];
12 char buffer[MAX_CHARS];
13 char word_wrap[MAX_LINE_LEN];
14
15 /* Functions */
16 void parameters(char [], FILE *);
17
18 /* Variables */
19 int width = 0;
20 int margin = 0;
21
22 /*
23 argc is the count of input arguments
24 *argv is a pointer to the input arguments
25 */
26 int main (int argc, char *argv[])
27 {
28 /* Creates file pointer */
29 FILE *fp = fopen(argv[1], "r"); /* r for read */
30
31 if (!fp) /* Error checking */
32 {
33 printf("Error: Could not open file");
34 return 0;
35 }
36
37 /* Retrieves width and margin parameters from input file */
38 parameters(input, fp);
39
40 fclose(fp); /* Closes file stream */
41
42 return 0;
43 }
44
45 void parameters(char input[], FILE *fp)
46 {
47 /* Gets input file text line by line */
48 while (fgets (input, 133, fp) != NULL)
49 {
50 /* Creates a pointer to traverse array */
51 char *p = input;
52
53 /* Checks for width parameter read in from text file */
54 if (input[0] == '?' && input [1] == 'w')
55 {
56 strtok(input, " "); /* Eliminates first token '?width' */
57 width = atoi(strtok(NULL, " ")); /* Stores int value of ASCII token
58 p = NULL;
59 }
60
61 /* Checks for margin parameter read in from text file */
62 if (input[0] == '?' && input[1] == 'm')
63 {
64 strtok(input, " "); /* Eliminates first token '?mrgn' */
65 margin = atoi(strtok(NULL, " ")); /* Stores int value of ASCII token
66 p = NULL;
67 }
68
69 if (p != NULL) /* skips printing format tokens at beginning of file */
70 {
71 if (width == 0) /* no width command, formatting is off by default */
72 {
73 printf("%s", p); /* Prints unformatted line of text */
74 }
75 else /* formatting is on */
76 {
77 printf("%*s" "%s", margin, " ", p); /* Prints formatted line of text
78 }
79 }
80 }
81 }
82
And here's an example input file, along with its proper output:
?width 30
?mrgn 5
While there are enough characters here to
fill
at least one line, there is
plenty
of
white space which will cause
a bit of confusion to the reader, yet
the ?fmt off command means that
the original formatting of
the lines
must be preserved. In essence, the
command ?pgwdth is ignored.
Output:
While there are enough
characters here to fill
at least one line, there
is plenty of white space
which will cause a bit of
confusion to the reader,
yet the ?fmt off command means that
the original formatting of
the lines
must be preserved. In essence, the
command ?pgwdth is ignored.
hi I have this question with reading data into array of structures
This is what i have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 20
#define FILE_NAME 50
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct
{
char *name;
int score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
char buffer[50];
int count = 0;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while (fgets(buffer, LIST_SIZE, fp) != NULL)
{
printf("%s\n", buffer);
list[count].name = (char*) calloc(strlen(buffer), sizeof(char));
sscanf(buffer,"%s%d", list[count].name, &list[count].score);
printf("name is: %s and score is:%d \n", list[count].name, list[count].score);
count++;
}
printf("Read in %d data records\n", count);
return 0;
}
so, inside the while loop when i try to print out with out allocating name it seems to work fine, but after i allocate memory for name the buffer is missing the first name when printing out.
so i have this output
Enter the file name: in.txt
Ada Lovelace, 66
Torvalds, 75
Norton, 82
Thompson, 82
Wozniak, 79
Andreessen, 60
Knuth, 60
Goldberg, 71
Hopper, 82
Joy, 91
Tanenbaum, 71
Kernighan, 72
Read in 12 data records
instead of the right output which is
Enter the file name: in.txt
Ada Lovelace, 66
Linus Torvalds, 75
Peter Norton, 82
Ken Thompson, 82
Steve Wozniak, 79
Marc Andreessen, 60
Donald Knuth, 60
Adele Goldberg, 71
Grace Hopper, 82
Bill Joy, 91
Andrew Tanenbaum, 71
Brian Kernighan, 72
Read in 12 data records
This is the output after i commented out the fscanf line, so I think the error may occur there.Is there something thing wrong with the memory allocation process, I'm thinking that I'm doing it wrong.
I fix the fscanf statement now i get
Enter the file name: in.txt
Ada Lovelace, 66
name is: Ada and score is:3929744
Linus Torvalds, 75
name is: Linus and score is:3929752
Peter Norton, 82
name is: Peter and score is:3929760
Ken Thompson, 82
name is: Ken and score is:3929768
Steve Wozniak, 79
name is: Steve and score is:3929776
Marc Andreessen, 60
name is: Marc and score is:3929784
Donald Knuth, 60
name is: Donald and score is:3929792
Adele Goldberg, 71
name is: Adele and score is:3929800
Grace Hopper, 82
name is: Grace and score is:3929808
Bill Joy, 91
name is: Bill and score is:3929816
Andrew Tanenbaum, 71
name is: Andrew and score is:3929824
Brian Kernighan, 72
name is: Brian and score is:3929832
Read in 12 data records
as you can see the line name is: only print out first name but not last name and the address of integer score.
The fgets and the fscanf are fighting with each other because they're both reading from the file. Use fgets to read from the file into your buffer, then use sscanf to parse the data into the structure.
In general you should prefer fgets to fscanf because it's safer. In any case, don't mix fgets and fscanf.
There are several problems with your code. First of all try using scanf and fscanf if there is a certain pattern in your input file. I have had problems with newline characters when using fgets and gets. Also fscanf reads till it finds either space character or the newline (have you considered this in your code? since it is very obvious why it reads only one of the name segments). It may be that your are using printf with the same problem, it only writes till \n or ' '.
You might wanna consider using ifstream and sstream if you can use C++.
Try this one:
...
while (fgets(buffer, LIST_SIZE, fp) != NULL)
{
char *tok;
printf("%s\n", buffer);
tok = strchr(buffer, ',');
if (!tok)
{
printf("Bad line\n");
continue;
}
list[count].name = strndup(buffer, tok - buffer);
list[count].score = atoi(tok + 1);
printf("name is: %s and score is:%d \n", list[count].name, list[count].score);
count++;
}
...