Program does not suppress integers, although float numbers are suppressed - c

I have a txt file like that:
alter_ego,simulation,pc,1985,0,0.03,0.03,5.8
simcity,simulation,pc,1988,0,0.02,0.03,2.2
doom,shooter,pc,1992,0.02,0,0.03,8.3
star_wars:dark_forces,shooter,pc,1994,1.09,0.77,1.95,7.7
battle_arena_toshinden,fighting,ps,1994,0.39,0.26,1.27,6.3
resident_evil,action,ps,1996,2.05,1.16,5.05,9
using this code, I write in another file like this:
alter_ego
simulation
pc
1985
0
0.03
0.03
5.8
simcity
simulation
pc
1988
0
0.02
0.03
2.2
doom
shooter
pc
1992
0.02
0
0.03
8.3
star_wars:dark_forces
shooter
pc
1994
1.09
0.77
1.95
7.7
...
however, when the program reaches an integer, it does not write that number to the file.(
for example, the 9 files at the end of the resident evil are not printed.)
#include <stdio.h>
int main(void){
char line[128];
char word[32];
FILE *in, *out;
int line_length;
in = fopen("in.txt", "r");
out = fopen("out.txt", "w");
while(1==fscanf(in, "%[^\n]%n\n", line, &line_length)){//read one line
int pos, len;
for(pos=0;pos < line_length-1 && 1==sscanf(line + pos, "%[^,]%*[,]%n", word, &len);pos+=len){
fprintf(out, "%s\n", word);
}
}
fclose(out);
fclose(in);
return 0;
}
how can I fix it?Thanks...

That's easy.
Here is my code:
#include <stdio.h>
int main()
{
int c;
while((c = getchar()) != EOF){
if(c == ',' || c == '\n')
printf("\n");
else
printf("%c",c);
}
}
in file.txt
alter_ego,simulation,pc,1985,0,0.03,0.03,5.8
simcity,simulation,pc,1988,0,0.02,0.03,2.2
doom,shooter,pc,1992,0.02,0,0.03,8.3
star_wars:dark_forces,shooter,pc,1994,1.09,0.77,1.95,7.7
battle_arena_toshinden,fighting,ps,1994,0.39,0.26,1.27,6.3
resident_evil,action,ps,1996,2.05,1.16,5.05,9
then run command:
gcc -o print print.c
./print < file.txt
That's all.

pos < line_length-1
is wrong - it is omitting last character. Just:
pos < line_length
Tested with:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
char str[] =
"alter_ego,simulation,pc,1985,0,0.03,0.03,5.8\n"
"simcity,simulation,pc,1988,0,0.02,0.03,2.2\n"
"doom,shooter,pc,1992,0.02,0,0.03,8.3\n"
"star_wars:dark_forces,shooter,pc,1994,1.09,0.77,1.95,7.7\n"
"battle_arena_toshinden,fighting,ps,1994,0.39,0.26,1.27,6.3\n"
"resident_evil,action,ps,1996,2.05,1.16,5.05,9\n";
int main(void){
char line[128];
char word[32];
FILE *in = fmemopen(str, sizeof(str), "r");
FILE *out = stdout;
int line_length;
while (1 == fscanf(in, "%127[^\n]%n\n", line, &line_length)) {//read one line
int pos, len, r;
for (pos = 0; pos < line_length &&
1 == sscanf(line + pos, "%31[^,]%*[,]%n", word, &len);
pos += len){
fprintf(out, "%s\n", word);
}
}
fclose(in);
fclose(out);
return 0;
}

Related

Outputting CRC32 hex from text inside .txt file using C on Ubuntu environment

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define LSIZ 128
#define RSIZ 10
int main()
{
// gets input from input.txt
char *filename = "input.txt";
FILE *fptr;
fptr = fopen(filename, "r");
int i = 0, j, tot = 0;
char line[RSIZ][LSIZ];
// inputs text content into array
while(fgets(line[i], LSIZ, fptr) != NULL)
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
printf("\n");
tot = i;
printf("\nThe content of the file %s are: \n",filename);
for(j = 0; j < tot; ++j)
printf(" %s\n", line[i]);
//convert into hex of crc32
const char *s = line[i];
printf("%s's crc32 in hex: ",filename);
printf("%lX\n", crc32(0, (const void*)s, strlen(s)));
return 0;
}
I can't seem to get the code to work as intended. I am using vim while also compiling on an Ubuntu Terminal for this code. I wanted this to get the text from input.txt, store it into the array and create crc32 hex of said input. However, this output is the result:
The content of the file input.txt are:
input.txt's crc32 in hex: 0
There is definitely something wrong with the char inputting but, after browsing, I seemed to hit the wall on this. Any help would be appreciated!
I edited your question, removing the answer you added to it, and posted that answer here.
My code is running perfectly now. I will write the the whole thing here for other's reference:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define LSIZ 128
#define RSIZ 10
int main(int argc, const char * argv[])
{
// gets input from input.txt
char *filename = "input.txt";
FILE *fptr;
fptr = fopen(filename, "r");
int i = 0, j, tot = 0;
char line[RSIZ][LSIZ];
// inputs text content into array
while(fgets(line[i], LSIZ, fptr) != NULL)
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
tot = i;
printf("The content of the file %s are: ",filename);
for(j = 0; j < tot; ++j)
printf("%s\n", line[j]);
//convert into hex of crc32
const char *s = line[0];
printf("%s's crc32 in hex: ",filename);
printf("%lX\n", crc32(0, (const void*)s, strlen(s)));
fclose(fptr);
return 0;
}
This is the output with "Hello World" inside input.txt file:
The content of the file input.txt are: Hello World
input.txt's crc32 in hex: 4A17B156

How to shuffle 2 different text file into 1?

#include <stdio.h>
int main(){
char temp[64];
FILE *fp1=fopen("data/1.txt","a");
FILE *fp2=fopen("data/2.txt","r");
while(fgets(temp,64,fp2)!=NULL){
fputs(temp,fp1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
With such code I was able to combine 2 different text file into 1.
data/1.txt contents: abcdefghijk
data/2.txt contents: ABCDE
Outcome: abcdefghijkABCDE
However, I am struggling with shuffling 2 different text file.
Wanted result: aAbBcCdDeEfghijk
Followings are my current code.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
fp1=fopen("data/1.txt","r");
fp2=fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
if(!strncmp("aAbBcCdDeEfghijk",buf,64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
How can I design a code in "shuffling code area" in order to have outcomes like wanted result? I have thought about making 2 different FOR loops and combining but it kept showed an error.
This is some dirty way to do the job.
You can read the file which ever you want to write first character first and then read a character from second file and write both into third file one after the other.
Just adding extra code as per your need.
This just works for your case , not tested with many cases and corner cases.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
int file1_content_over = 0;
int file2_content_over = 0;
fp1 = fopen("data/1.txt","r");
fp2 = fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
// read till file1_content_over or file2_content_over is not finished
while(! file1_content_over || !file2_content_over)
{
ch1 = fgetc(fp1);
ch2 = fgetc(fp2);
if(ch1 != EOF)
fputc(ch1,fp_out);
else
file1_content_over = 1;
if(ch2 != EOF)
fputc(ch2,fp_out);
else
file2_content_over = 1;
}
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
printf("buf = %s\n", buf);
if(!strncmp("aAbBcCdDeEfghijk",buf,strlen("aAbBcCdDeEfghijk")))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
Working for me! Not the best optimized code, I didnt get to much time to that!
Main():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
int removingSPaces(char array[MAX], int sizeArray);
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2);
int getChar(char buf[MAX], FILE *fp);
int main(){
FILE *fp1, *fp2, *fpOut;
char bufFile1[MAX] = {0}, bufFile2[MAX] = {0}, bufOut[MAX] = {0};
int sizeBuf1 = 0, sizeBuf2 = 0;
int maxSize=0;
if((fp1=fopen("file1.txt","r")) == NULL || (fp2=fopen("file2.txt","r")) == NULL || (fpOut=fopen("fileOut.txt","w")) == NULL){
perror("");
exit(1);
}
sizeBuf1 = getChar(bufFile1, fp1); //geting the chars from file1
fclose(fp1);
sizeBuf1 = removingSPaces(bufFile1, sizeBuf1); //removing the \n if exists from chars of file1
sizeBuf2 = getChar(bufFile2, fp2); //geting the chars from file2
fclose(fp2);
sizeBuf2 = removingSPaces(bufFile2, sizeBuf2); //removing the \n if exists from chars of file2
maxSize = sizeBuf1 + sizeBuf2; //Max Size to loop for
orderChar(bufFile1, bufFile2, bufOut, maxSize, sizeBuf1, sizeBuf2); //Order the chars!
fprintf(fpOut, "%s", bufOut); //Printing to the file
fclose(fpOut);
/* COPIED FROM YOUR CODE */
char buf[64]={0}; //Just added the 0, because you cant initialize the array like with only {}
if((fpOut=fopen("fileOut.txt", "r")) == NULL){
perror("");
exit(1);
}
fgets(buf,64, fpOut);
if(!strncmp("aAbBcCdDeEfghijk", buf, 64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fpOut);
/* COPIED FROM YOUR CODE */
return 0;
}
Functions():
int removingSPaces(char array[MAX], int sizeArray){
int size = sizeArray;
if(array[sizeArray -1] == '\n'){
array[sizeArray -1] = '\0';
size = strlen(array);
}
return size;
}
int getChar(char buf[MAX], FILE *fp){
char bufAux[MAX];
int size;
while(fgets(bufAux, sizeof(bufAux), fp)){
size = strlen(bufAux);
}
strcpy(buf, bufAux);
return size;
}
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2){
int positionsF1=0, positionsF2=0;
int aux = 0; //This will starts organization by the first file! If you want to change it just change to 1;
for(int i=0; i < maxSize; i++){
if(aux == 0 && positionsF1 != sizeBuf1){
bufOut[i]=bufFile1[positionsF1];
if(positionsF2!=sizeBuf2){
aux = 1;
}
positionsF1++;
}else if(aux == 1 && positionsF2 != sizeBuf2){
bufOut[i]=bufFile2[positionsF2];
if(positionsF1!=sizeBuf1){
aux = 0;
}
positionsF2++;
}
}
}
Content of file 1:
abcdefghijk
Content of file 2:
ABCDE

How to read in a file but skip characters after #?

Have a problem to read in a file in c. Have been searching online since I'm a beginner in programming but still I have a problem with the output of my file.
int main( int argc, char *argv[]){
FILE *in;
int chr;
if(in = fopen("airmap1.map", "r")) == NULL){
printf("Could not open file\n");
exit(1);
while(fgets(row, sizeof(row),in) !=NULL){
if (*row == '#') //next row
continue;
fscanf(in, "%*[^\n]s , %[]s", row);
}
}
The file I want to read in is looking like this:
#animals at the zoo
cat dog #cat-dog
fish frog #fish-frog
I want to ignore comments after this sign #, but my problem is that my code only ignore the first word after #. But right now it gives me this output:
cat frog
dog fish
How can i solve this problem? I would like to have the output this form instead:
cat dog
fish frog
You could use a function that checks for any "#" in every line of the file, and then copy it in another string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define commentSign '#'
#define bufferLength 255
int findPosOfChar(char * buffer, char charToFind, int length)
{
int i;
for(i = 0 ; i < length ; i++)
{
if(buffer[i] == charToFind)
return i;
}
return 0;
}
int main( int argc, char *argv[]){
FILE* filePointer = fopen("test", "r");
char buffer[bufferLength];
char *p = malloc(sizeof(char) * 255);
int commentPos;
while(fgets(buffer, bufferLength, filePointer)) {
commentPos = findPosOfChar(buffer, (char)commentSign, bufferLength);
memcpy(p, buffer, commentPos);
p[commentPos] = '\0';
printf("%s\n", p);
}
fclose(filePointer);
}

How to split a text file into multiple parts in c

What i need to do, is to take a file of n lines, and for every x lines, create a new file with the lines of the original file. An example would be this:
Original File:
stefano
angela
giuseppe
lucrezia
In this case, if x == 2, 3 file would be created, in order:
First file:
stefano
angela
Second FIle:
giuseppe
lucrezia
Third File:
lorenzo
What i've done so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * filename = malloc(sizeof(char)*64);
char * ext = ".txt";
char number[2];
for(int i = ix; i < *mem; i++)
{
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && (ix*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
I'm stack with segmentation error, i couldn't find the bug doing
gdb myprogram
run
bt
I really appreciate any help.
EDIT:
I've changed some things and now it works, but it creates an additional file that contains strange characters. I need to still adjust some things:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * ext = ".txt";
for(int i = ix; i < *mem; i++)
{
char * filename = malloc(sizeof(char)*64);
char * number = malloc(sizeof(char)*64);
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
free(number);
free(filename);
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && ((ix-1)*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
There are a few problems in your code. But first I think you need to fix the most important thing
int step = lines/N;
Here step is 0 if your input file has less than N lines of text. This is because lines and N both are integer and integer division is rounding down.
I won't fix your code, but I'll help you with it. Some changes I
suggest:
Instead of getlines, use getline(3) from the standard
library.
fseek(fp, 0 , SEEK_SET) is pointless.
In char * filename = malloc(sizeof(char)*64), note that
both arguments to malloc are constant, and the size is arbitrary.
These days, it's safe to allocate filename buffers statically,
either on the stack or with static: char filename[PATH_MAX].
You'll want to use limits.h to get that constant.
Similarly you have no need to dynamically allocate your FILE
pointers.
Instead of
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
use sprintf(filename, "temp%d%s", i+1, ext)
get familiar with err(3) and friends, for your own convenience.
Finally, your recursive Split is -- how shall we say it? -- a nightmare. Your whole program
should be something like:
open input
while getline input
if nlines % N == 0
create output filename with 1 + n/N
open output
write output
nlines++

How to read a text file 3 characters at a time?

I'm learning to program in C, and right now my homework is like this. I am supposed to be able to take a text file with words/letters and my program should print the ascii codes+1 of the letters it gets. It's "encoding" it. So for example the letter "A" would be printed as 066. So my problem is the program needs to also be able to decode those ascii codes back to letters, but I don't know how to get my program to read 3 numbers at once. I used
c = fgetc(pF);
while (c != EOF) {
fprintf(pF2,"%03i",c+1);
c = fgetc(pF);
to read the file one character at a time. Should I use something similar to get the 3 numbers I need, or would it be something completely different?
#include "stdio.h"
#include "stdlib.h"
int encode(){
char * fName = "testR.txt";
char * fName2="testW.txt";
FILE * pF;
FILE * pF2;
char c, cArray[500];
int i=0;
pF = fopen(fName, "r");
if ( pF == NULL ) {
printf("Error: The specified file could not be opened.\n");
return -1;
}
pF2 = fopen(fName2, "w");
c = fgetc(pF);
while (c != EOF) {
fprintf(pF2,"%03i",c+1);
c = fgetc(pF);
}
fclose(pF);
fclose(pF2);
return;
}
char decode(){
char * fName = "testW.txt";
char * fName2="testW2.txt";
char * buf;
FILE * pF;
FILE * pF2;
char cArray[500];
char buffer[4];
buffer[3] = '\0';
pF = fopen(fName, "r");
if ( pF == NULL ) {
printf("Error: The specified file could not be opened.\n");
return -1;
}
pF2 = fopen(fName2, "w");
while (fread(buffer, 3, 1, stdin)){
putchar((atoi(buffer)-1) & 0xFF);
}
fclose(pF);
fclose(pF2);
}
int main (int argc, char *argv[]){
char c;
if ( argc != 2 ) {
printf("Incorrect number of arguments.\n");
exit(-1);
}
if (strcmp(argv[1], "-e") == 0){
encode();
}
if (strcmp(argv[1], "-d") == 0){
decode();
}
return 0;
}
I am aware that my code is a mess and there are probably things that shouldn't be there from all the changes I've been trying to make =[
Encoding:
int c;
while ((c = getchar()) != EOF)
printf("%.3d", (c+1)&0xFF);
Decoding:
char buffer[4];
buffer[3] = '\0';
while (fread(buffer, 3, 1, stdin))
putchar((atoi(buffer)-1) & 0xFF);
Technically, if the output does not end with a newline when encoding, the output is not a text file. There's no error checking on the input. The fread() will return 1 when it reads a triplet of characters; otherwise, it will return 0.
Working Programs
e3.c — encryption
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
printf("%.3d", (c+1)&0xFF);
return 0;
}
d3.c — decryption
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buffer[4];
buffer[3] = '\0';
while (fread(buffer, 3, 1, stdin))
putchar((atoi(buffer)-1) & 0xFF);
return 0;
}
Sample output
$ e3 < e3.c
036106111100109118101102033061116117101106112047105063011011106111117033110098106111041119112106101042011124011033033033033106111117033100060011011033033033033120105106109102033041041100033062033104102117100105098115041042042033034062033070080071042011033033033033033033033033113115106111117103041035038047052101035045033041100044050042039049121071071042060011033033033033115102117118115111033049060011126011011$
$
The dollar at the end of the line is the prompt.
$ e3 <e3.c | d3
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
printf("%.3d", (c+1)&0xFF);
return 0;
}
$ e3 <e3.c | d3 | diff e3.c -
$
Basic round-tripping the encoding and decoding shows that the code works.
while (fread(buf, 1, 3, pF) == 3)
{
...
}

Resources