fgets reading in spaces when there are none - c

Using fgets() to read in strings.
But the print statement that prints the size prints out 4 when my input is a 3 character string "abc".
This ruins my methods completely because it adds a space to the char array making arrange not work.
Input file:
2
abc
bca
I'm sure there is no space after the strings.
int main(){
FILE * inF;
inF = fopen ("input2.txt", "r");
//Find number of Strings
int numWords = 0;
fscanf(inF, "%d", &numWords);
printf("%d\n", numWords);
int i = 0;
int counter = 0;
char string[10000];
//Run fgets so it starts at second line
fgets(string, 20, inF);
while(i< numWords) {
string[10000] = 0;
fgets(string, 20, inF);
printf("char: %s", string);
//find and print permutations
counter = strlen(string);
printf("size: %d\n", counter);
arrange(string, 0, counter - 1);
i++;
}
return 0;
}
Any help would be great, thanks!

The first fscanf reads the number, but leaves the newline. So when you later call fgets it is this empty line that fgets reads.
Use only fgets to get complete lines, and if you need to use a scanf like function then use sscanf on that line.

Don't mix fscanf() and fgets().
Read a whole line for the first line, then use sscanf() to parse out the number from that line, before continuining with more fgets() to read remaining lines.

You may print what's in the buffer string[] after fgets, like this:
...
while(i< numWords) {
string[10000] = 0; // !!! Do you mean string[9999] = 0;
fgets(string, 20, inF);
printf("char: %s", string);
// add printf here
for (j = 0; j < 20; j++)
printf("%02X ", (unsigned char)string[j]);
printf("\n");
...
}
and you would see the result like this:
2
char: abc
61 62 63 0A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
size: 4
char: bca
62 63 61 0A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
size: 4
As you can see, there is a 0A, i.e., \n, after every fgets. Then it would be obvious why the size is 4.
$ man fgets
...
If a newline is read, it is stored into the buffer.
...
So you may have to remove the newline manually.

Related

Does fgets store a newline or just \0?

I am confused. Over the internet you can see different answer, so what is the real answer? Thanks.
What will be stored in name?
Assume the user types the following:
JennyENTER
20ENTER
void function()
{
int product;
char name[10];
fgets(name, 10, stdin);
scanf("%d", &product);
}
A. Jenny\0
B. Jenny\n\0
When the input is short enough to fit, the newline will be included.
If the data before the newline is 9 characters or more (for the code above), the newline will not be included and the extra characters and newline will be left in the input stream to be read by another input call. If you enter Jenny (and a newline), the newline will be included. If you enter Jennifer, you also get the newline, but if you enter Stephanie and a newline, you don't get the newline (it's left behind to be read by another input function). If you enter Antidisestablishmentarianism, you get the input string Antidises\0, and tablishmentarianism is left for other input code to read.
Check out this small program.
When running, give inputs with length greater than 10 and less than 10.
You see that a new line (10)dec will be stored before storing \0 if input length is less than 10.
#include <stdio.h>
int main()
{
char str[10] = {0};
int i = 0;
fgets(str,sizeof(str),stdin);
while(str[i])
{
printf("%d %d = %c\n" ,i, str[i], str[i]);
i++;
}
printf("%d %d = %c\n" , i, str[i], str[i]);
return 0;
}
ABCDEFGHIJKLM
0 65 = A
1 66 = B
2 67 = C
3 68 = D
4 69 = E
5 70 = F
6 71 = G
7 72 = H
8 73 = I
9 0 =
HELLO
0 72 = H
1 69 = E
2 76 = L
3 76 = L
4 79 = O
5 10 =
6 0 =

program to compress a fileinto run-length code in C

I am writing a program to compress a file consisting of hexadecimal values into run-length code. For example, given a file:
46 6f 6f 20 62 61 72 21 21 21 20 20 20 20 20
my code should produce the following file:
01 46 02 6f 01 20 01 62 01 61 01 72 03 21 05 20
I don't know why the program I've written gets stuck. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
int main(void){
int a, b, c, count=1, flag=TRUE;
FILE *file;
FILE *out;
file = fopen("input.txt", "r");
if(file){
out = fopen("input.txt.out", "a");
fscanf(file, "%x", &a);
while(fscanf(file, "%x", &c)){
while(flag==TRUE){
if(c==a){
count= count+1;
}else{
flag = FALSE;
}
b=a;
a=c;
}
fprintf(out, "%d %02x ", count, b);
count = 1;
flag = TRUE;
}
}else{
printf("ERROR: file not found.");
}
}
EDIT: I updated the code removing the !feof(file) argument and replacing it with an actual I/O function instead. Thanks for the insight. However, my program still doesn't work.
I don't know why your program "gets stuck" but this might work better. Note I have dumped the meaningless a, b, c and the truth stuff.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int lastchar, thischar, count;
FILE *finp;
FILE *fout;
finp = fopen("input.txt", "r");
fout = fopen("output.txt", "w"); // changed "a" to "w"
if(fout == NULL || finp == NULL) {
puts("Error opening file(s)");
exit(1);
}
count = 1;
fscanf(finp, "%x", &lastchar);
while(fscanf(finp, "%x", &thischar) == 1) { // func value better then feof
if(thischar == lastchar) {
count++;
}
else {
fprintf(fout, "%02X %02X ", count, lastchar);
count = 1;
}
lastchar = thischar;
}
fprintf(fout, "%02X %02X ", count, lastchar); // discharge remaining
fclose(fout);
fclose(finp);
return 0;
}
Program input: 46 6f 6f 20 62 61 72 21 21 21 20 20 20 20 20
Program output: 01 46 02 6F 01 20 01 62 01 61 01 72 03 21 05 20
A better way of implementing RLE is to choose an "escape" value to define when a compression follows. Thus 3 values will encode a compression sequence, and so it is only worth compressing 3 or more the same. All other characters are verbatim, except the escape character itself.

i'm not processing more than one block correctly

I have an assignment where I'm suppose to read input lines such as
2
67 5 100 1 11 97 98 10 1 110
15 72 10 101 47 67 88 20 94 6 22 11
4
61 11 93 4 73 39 78 34 17 104
23 43 11 93 65 52 20 96 66 31 86 24 40 61 102 13 50 51
73 43 28 73 8 89 31 68 77 27 24 77 42 72 15 24 64 51
25 75 7 90 10 111 17 16
.....
process every two integers (the first line in a block only tells us how many words we will process), add them then match
them to their corresponding ASCII char. The example above would be two blocks.
The output should be:
Decoded messages:
Hello World!
Happy Bhutanese teacher's day!
I'm having problems when it comes to dealing with a file with multiple blocks, more than 20 and so forth following the same format on one input text. I can handle one block fine, two blocks okay but not fine because my program doesn't seem to end. No line will be longer than 256 characters. numOfPuzzl refers to how many words we process per block.
I'd greatly appreciate any help. I attached my code and commented as much as I can too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
//user will type in file name they choose to process and we allocated in filename[]
char filename[256];
printf("Enter filename: ");
scanf("%s", filename);
//process filename username typed in
FILE *pFile;
pFile = fopen(filename, "r");
//if there's nothong to read
if (pFile == NULL){
exit(1);
}
printf("Decoded messages:\n");
//create array we will putting lines into
char myString[256];
//simply gets the first line, which is always a lone integer
fgets(myString, 256, pFile);
int numOfPuzzl;
sscanf(myString, "%d", &numOfPuzzl);
//printf("puzzles to solve: %d\n", numOfPuzzl);
int wordsProcessed = 0;
//just remember that myString has entire line
//start processing the lines that follow, a line is a word
while (fgets(myString, 256, pFile) != NULL){
int num = 0; //first integer in line
int secondNum = 0; //second int. in line
int tot = 0; //how many bytes
int bytes_read = 0; //bytes processed
char *endOfStrAdr = strchr(myString, '\0'); //returns address of end terminating char.
int endOfStrIdx = endOfStrAdr - myString; //this will give me the index of where the terminating char. occurs within my array
//start scanning integers within array making sure to not sccan out of bounds
while (tot < endOfStrIdx){
//first integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &num, &bytes_read);
tot += bytes_read; //keeps tab so we don't have to read from the begn. of array everytime
//second integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &secondNum, &bytes_read);
tot += bytes_read; ////keeps tab so we don't have to read from the begn. of array everytime
printf("%c", (char) num + secondNum); //add the two integers and cast them to char
//we want to check if we are the end of the string, our word
if (tot == endOfStrIdx){
printf(" ");
wordsProcessed++;
//we want to print a new line char. if we finished processing all the words for the puzzle
if (wordsProcessed == numOfPuzzl){
printf("\n");
fgets(myString, 256, pFile);
}
}
}
}
fclose(pFile);
}
Ignore blank lines between puzzles.
Reset parameters (numOfPuzzl and wordsProcessed) before processing new puzzles.
To archive that, change
if (wordsProcessed == numOfPuzzl) {
printf("\n");
fgets(myString, 256, pFile);
}
into
if (wordsProcessed == numOfPuzzl) {
printf("\n");
while ( fgets(myString, 256, pFile) != NULL ){
if ( sscanf(myString, "%d", &numOfPuzzl) == 1 )
break;
}
wordsProcessed = 0;
}
I suggest like this:
#include <stdio.h>
#include <stdlib.h>
//stringize macro
#define S_(x) #x
#define S(x) S_(x)
int main(void){
char filename[FILENAME_MAX + 1];
printf("Enter filename: ");
scanf("%" S(FILENAME_MAX) "[^\n]", filename);
FILE *pFile;
if(NULL==(pFile = fopen(filename, "r"))){
perror("can't opne file");
exit(EXIT_FAILURE);
}
printf("Decoded messages:\n");
int numOfLines;
while(1==fscanf(pFile, "%d", &numOfLines)){
for(int i = 0; i < numOfLines; ++i){
int num1, num2, state;
char ck;
while(3==(state=fscanf(pFile, "%d %d%c", &num1, &num2, &ck)) || 2 == state){
putchar(num1 + num2);
if(state == 2 || state == 3 && ck == '\n')
break;
}
putchar(' ');
}
putchar('\n');
}
fclose(pFile);
return 0;
}

Program is removing spaces in string uninteded

I am a beginner programmer taking a class and I cannot get my output strings to print with spaces in between words. Here is my code below. It is supposed to take a string that I input and either change to all caps or all lower case as I specify when I run the program. If I put in MY CODE DOES NOT WORK, it outputs mycodedoesnotwork. Why is it removing the spaces?
1 #include <stdio.h>
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6
7 int shout(char * msgIn, char * msgOut) {
8
9 if (!msgIn || !msgOut)
10 return -1;
11 while (*msgIn != '\0') {
12 if ('a' <= *msgIn && *msgIn <= 'z')
13 *msgOut = *msgIn + ('A' - 'a');
14 else
15 *msgOut = *msgIn;
16 msgIn++;
17 msgOut++;
18 }
19 *msgOut = '\0';
20
21 return 0;
22 }
23
24
25 int whisper(char const * msgIn, char * msgOut) {
26 if (!msgIn || !msgOut)
27 return -1;
28 while (*msgIn != '\0') {
29 if ('A' <= *msgIn && *msgIn <= 'Z')
30 *msgOut = *msgIn + ('a' - 'A');
31 else
32 *msgOut = *msgIn;
33 msgIn++;
34 msgOut++;
35 }
36 *msgOut = '\0';
37 return 0;
38 }
39
40 int main(int argc, char ** argv) {
41 char in[128], out[128];
42 int i;
43 for (i = 1; i < argc; i++) {
44 if (strcmp("-w", argv[i]) == 0)
45 while (scanf("%s", in) != EOF) {
46 whisper(in, out);
47 printf("%s", out);
48 }
49 else if (strcmp("-s", argv[i]) == 0)
50 while (scanf("%s", in) != EOF) {
51 shout(in, out);
52 printf("%s", out);
53 }
54 }
55 printf("\n");
56 return 0;
57 }
~
~
The scanf calls are reading in just the words (no spaces) and you are not adding spaces back in when you output your strings.
If you don't mind a trailing space, just change lines 47 and 52 to printf("%s ", out)
while (scanf("%s", in) != EOF)==> scanf() takes input up to space and send to function
and then in next iteration again takes word after space.
You need to use fgets() instead.
It is not problem with your shout() or wisper() functions, but problem with scanf().
When you specify %s to read string, the string will terminate at any white space chars - space, tab etc.
And that will not be included in the string. So space that you enter between the strings are not stored in in variable.
You may want to think of different approach to solve that.
The space is a string terminator for scanf() and scanf() does not include it in the acquired string. man 3 scanf

How would I print out the address like the Hexdump function in UNIX

There I have this assignment where I am suppose to emulate the hexdump function from unix. I got my program to dump files into hex but i am having trouble printing the offset and the printable characters.
Here is my code:
/*performs a hex and an octal dump of a file*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 512
void hexdump(FILE *fp);
void octaldump(FILE *fp);
int main(int argc, char * argv[])
{
FILE *fp;
if((fp = fopen(argv[1], "rb+")) == '\0')
{
perror("fopen");
return 0;
}
hexdump(fp);
return 0;
}
void hexdump(FILE *fp)
{
char temp [LINESIZE];
size_t i = 0;
size_t linecount = 1;
long int address = 0;
while(fscanf(fp," %[^\n] ", temp) == 1)
{
printf("%5d", address);
for(i = 0; i < strlen(temp); i++)
{
printf("%02x ", temp[i]);
if(linecount == 16)
{
printf("\n");
linecount = 0;
}
linecount++;
}
printf(" | ");
for(i = 0; i < strlen(temp); i++)
{
if(temp[i] < 32)
{
printf(".");
}
else
{
printf("%c", temp[i]);
}
}
printf("\n");
}
}
As i said above, my program is suppose to print the offset then the hex value of the file padded with 0's, then the printable characters of the file like so.
0000000 7f 2a 34 f3 21 00 00 00 00 00 00 00 00 00 00 00 | test file
I managed to print out the printable characters, but they appear after the hex part. So if one line of hexcode extends to the next line, it prints the printable characters on the nextline.
For example:
2a 3b 4d 3e 5f
12 43 23 43 | asfdg df
How do i get it to print whatever character appears after one line of the hex characters?
PS: For some reason my program doesn't pad 0's for some reason.
EDIT1: I got the offset part, i just keep adding 16 to my address variable and keep printing
Since this is homework, I'll just give you some pointers on how to approach your problem. I'll be as vague as I can so as to not interfere with your learning.
First of all, don't use fscanf if you're writing a hex dumper, use fread instead. The scanf family of functions are meant for text and hex dumpers are usually used with binary data.
If you use fread and read just enough bytes at a time to fill one line of output, then you can produce your desired output with two for loops (one for hex, one for characters) followed by a single newline.
As far as your zero padding problem goes, read the printf man page, your "%5d" format string needs a little bit more.

Resources