How to print a substring in C - c

simple C question here!
So I am trying to parse through a string lets say: 1234567W
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
}
}
return 0;
My output so far shows: "123d" because of the "%.4sd" in the printf function.
I now need to get the next two numbers, "45". Is there a regex expression I can use that will allow me to get the next two digits of a string?
I am new to C, so I was thinking more like "%(ignore the first 4 characters)(print next 2 digits)(ignore the last two digits)"
input: pic
output: pic
Please let me know.
Thanks all.

printf("Next two: %.2s\n", p + 4); should work.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
printf("Next two: %.2s\n", p + 4);
}
}
return 0;
}
Side note: I added a missing stdio.h include. Please turn on compiler warnings, since this error would've been caught by them.

Related

Bad file descriptor error by working on files

C.
bad file descriptor error by working on files.
This is an assignment for college. I need to compress file txt and then to uncompress it. The compress method working fine
and it compresses by the idea that the last binary digit (Msb) is zero always in any ASCII char.
Does anybody know why it happens?
The problem happens when I do fgetc(input_file_8to7) in the uncompress method
The mainly problem is that i get -1 from the 2 fgetc(input_file_8to7) in uncompresd method
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdint.h>
the input for the uncompress is the output of the compress , the input is txt file that conatain the next 2 lines:
A hex dump is a hexadecimal view of computer data, from memory or from a computer file.
***compres method***
void compress8to7(FILE *input,FILE* output8to7)
{
// 0x00 87 00 87 00 87 00 87 ll
uint64_t magic=0x87008700870087ll;
uint64_t inputsize=0;
fwrite(&magic,sizeof (magic),1,output8to7);
fwrite(&inputsize,sizeof(inputsize),1,output8to7);
unsigned char st;
unsigned char st2;
char check;
char check2;
char shift=7;
char shift_st=0;
unsigned char inbfile;
// will contain the resullt of the asked new binary lines comprees
int breakflag=0;
int breakflag2=0;
int cnt=-1;
//this parameter will help to know when we dont need to move 1 back in
the pointer of input file
while(1) {
cnt++;
if (ftell(input)>1 && cnt%7!=0) //
{
fseek(input,-1 ,SEEK_CUR) ;
}
check = fgetc(input);
st=check;
if(check2==EOF){breakflag2=1;}
check2 = fgetc(input);
> //if the length is odd number check2 will get the eof
st2=check2;
if(check==EOF){breakflag=1;}
st2=st2<<shift;
> //move the digit to the right position
bit manipulation
st=st>>shift_st;
shift_st++;
if(shift_st==7)
{shift_st=0;}
shift=shift-1;
if(shift==0)
shift=7;
if(breakflag2!=1)
{inbfile=st2|st;
}else{ inbfile=st; }
fwrite(&inbfile, sizeof(inbfile),1,output8to7);
write to the file
if(feof(input))
{
inputsize= ftell(input);
fseek(output8to7,8,SEEK_SET);
fwrite(&inputsize,sizeof (inputsize),1,output8to7);
// if(breakflag==1)
break;}
}
}
*** uncompress method***
the problem is in this method
void uncompress8to7 (FILE *input_file_8to7 ,FILE *output_file_txt){
char st;
char st2;
char check;
char check2;
char shift2 = 7;
char shift_st = 0;
char shift_helper=7;
char shift_helper2=6;
char sthelper;
char sthelper2;
char inbfile; // will contain the resullt of the asked new binary lines comprees
int breakflag = 0;
int breakflag2 = 0;
int cnt = -1;//this parameter will help to know when we dont need to move 1 back in the pointer of input file
rewind(input_file_8to7);
printf("%d",ftell(input_file_8to7));
fseek(input_file_8to7,16,SEEK_SET);
printf("\n%d",ftell(input_file_8to7));
int a=0;
while(1) {
cnt++;
if(cnt>1) //
{fseek(input_file_8to7,-1 ,SEEK_CUR);}
printf("\n%d",ftell(input_file_8to7));
from that fgetc i get the bad file descriptor erorr
check = fgetc(input_file_8to7);
if(ferror(input_file_8to7)){
perror("eror by perror");
printf("file erorr");}
// printf("\n%d",ftell(input_file_8to7));
st = check;
check2 = fgetc(input_file_8to7);
st2 = check2;
if(cnt<2)
fseek(input_file_8to7,0,SEEK_SET);
if(check2==EOF){
breakflag2 = 1;
}
sthelper2=st2;
sthelper2=sthelper2>>shift_helper2;
st2=st2<<shift2;
st2=st2>>shift2;
sthelper=st;
sthelper=sthelper>>shift_helper;
sthelper=shift_helper<<shift_helper-1;
st=st<<shift_st;// to make all zero after the msb
st=st>>shift_st;// to make all zero after the msb
shift_helper2--;
if(shift_helper==-1)
{shift_helper2=6;}
shift_helper--;
if(shift_helper==-1){
shift_helper=7;
}
shift_st++;
if(shift_st==7)
{shift_st=0;}
shift2=shift2-1;
if(shift2==0)
shift2=7;
if(breakflag2==1)
{break;}
if(cnt%7==0){
inbfile=st;
}else{
inbfile=sthelper|st2;
}
writing to the file
fwrite(&inbfile,sizeof(inbfile),1,output_file_txt);
break the loop when we got to the end of file
if(feof(input_file_8to7))
{ break;}
}
}
***main***
int main(int argc, char **argv) {
char* input=NULL;
char* output8to7=NULL;
input=argv[1];
output8to7=argv[2];
open files
FILE* inputfile = fopen(input, "r");
if(inputfile==NULL)
{
printf("couldnt open input file ");
exit(-1);
}
FILE* file8to7=fopen(output8to7, "wb");
if(file8to7==NULL)
{
printf("couldnt open output file");
printf(output8to7);
exit(-1);
}
compress
compress8to7(inputfile,file8to7);
FILE* file8to7input=fopen("exampleout.bin", "ab");
FILE* output_file=fopen("UNoutput_file2.txt", "wb");
if(output_file==NULL)
{printf("couldnt open output file");
exit(-1);
}
uncompress8to7(file8to7input,output_file);
fclose(output_file);
fclose(file8to7input);
fclose(inputfile);
fclose(file8to7);
return 0;
}
This is the code to open the file:
FILE* file8to7input=fopen("exampleout.bin", "ab");
This opens it as an output file in append mode. You're trying to read from it in the uncompress8to7() function. You need to open it as in input file in read mode. Change that line to:
FILE* file8to7input=fopen("exampleout.bin", "rb");

Get the user to enter a name but using file stream *fp

I am a beginner in c so I have a problem with get the user to input last name, a comma & then first name. However it will pass to the function call
int get_name(FILE *fp)
in my main function. I have a problem either if I have to use the arguments parameters.
Example, main (int argc, char *argv[])) or just main (void))
and from what I have been searching so far, FILE*fp cannot get the user to enter from stdin it only use to open the file(?) BUT I am required to get the user to input from keyboard and pass to the function. I have written some codes. but they don't seem to work but I am going to put down on here the one I am sure that I need a few changes most.
#define LINESIZE1024
int main(void){
FILE *fp;
char line[LINESIZE];
char first;
char last;
char comma;
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(fp = (sscanf(line,"%s %s %s",&last,&comma,&first)==3))
get_name(fp);
if(get_last_first(fp)== -1)
break;
printf("Please enter first name a comma and then last name");
}
BUT I got an error saying I can't use pass it from pointer to an integer. and many MORE but I accidentally closed my concolse and all the errors that appeared while I was trying to fix are gone. So please give me some ideas.
What about seconde code
while(1){
if(!fgets(line,LINESIZE,fp)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s %s %s",last,comma,first)==3)
get_last_first(fp);
return 0;
}
It gave me errors too. fp,last,first,comma used uninitialized in this function
OK so I think I have fixed the previous problem now. However it doesn't print the name back if the name is given correctly. Here is my fixed main code.
int main(void){
FILE *fp = stdin;
char line[LINESIZE];
char first[16];
char last[16];
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s ,%s",last,first)==2)
if(get_name(fp)==2)
printf("Your name is: %s %s\n", first, last);
}
return 0;
}
here is my function.
int get_name(FILE *fp){
char line[LINESIZE];
char last[16], first[16];
int n;
/* returns -1 if the input is not in the correct format
or the name is not valid */
if(fgets(line, LINESIZE, fp) == NULL) {
return -1;
}
/* returns 0 on EOF */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == EOF) {
return 0;
}
/* prints the name if it's valid */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == 2) {
return 2;
}
return 1;
}
I thank you people so much for taking time to read and help me. Please don't be mean :)
Seems that you are making it more complicated than needed. Don't call fgets and scanf in main. Only do that in the function get_name.
It can be something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 1024
int get_name(FILE *fp)
{
char line[LINESIZE];
char* t;
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
t = strstr(line, ",");
if (t)
{
*t = '\0';
++t;
printf("First: %s - Last: %s\n", line, t);
return 2;
}
printf("Illegal input\n");
return 0;
}
int main(int argc, char **argv)
{
get_name(stdin);
return 0;
}
If you later decide that you want to read from a file, you can reuse the function get_name without changing it at all. All you need is to change main. Like:
int main(int argc, char **argv)
{
FILE* f = fopen("test.txt", "r");
if (f)
{
get_name(f);
fclose(f);
}
else
{
printf("Open file failed\n");
}
return 0;
}
If you want to read from the keyboard, read from stdin or use scanf, which internally reads from stdin. If you want to read from a file instead, use FILE *fp, but don't forget to open the file and check if it was successful (you'll find lots of tutorials for this).
Further, when reading in strings, you need an array of characters, not a single one. Note further, that scanf can already deal with formats like "everything that is not a ',' then a ',' then a string. Note that format "[^,]" means "any character except a ',':
So you could adapt the code as follows:
#define LINESIZE 1024
int main(void){
char line[LINESIZE];
char first[LINESIZE];
char last[LINESIZE];
while(fgets(line,LINESIZE,stdin)) {
if(sscanf(line,"%[^,],%s",last,first)==2) {
printf("Read in %s ... %s\n",last,first);
}
else {
printf("Please enter first name a comma and then last name");
}
}
return 0;
}
And if your professor is picky concerning the "use FILE*", you could write:
FILE *fp = stdin;
...
while(fgets(line,LINESIZE,fp)) {
...

Print out first line of input file char by char, but nothing comes to screen

So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}

File Input Ouput, reading multiple files in C

im trying to do a practice problem from my textbook and im having alot of trouble. Im trying to open files in an range that the user specifies, and doing calculations, moving from file to file. Each file has the following format file05-data-(int 1-99). and the whole file is called practice.exe My main function has the follwing parameters and looks like... say user enters the executable ./practice 10 13
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE* newfile;
int i = argc;
while (i<arvf[]) */im pretty sure i<arvf doesnt work but how do i capture
the range inputed by the user,and open each one?*/
{
newfile = fopen(("file05-data-%d.txt",i) "r")
i = i + 1
}
Im confused on how to take the user input, and opening the files in the range that the user inputed. Any help would be appreciated.
E.g
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
FILE *file;
if(argc != 3){
fprintf(stderr, "Usage >practice start_num end_num\n");
return 1;
}
int start = atoi(argv[1]);
int end = atoi(argv[2]);
if(!(1 <= start && start <= 99 && 1<= end && end <= 99 && start <= end)){
fprintf(stderr, "Specifying the range of values must be 1-99.\n");
return 2;
}
char filename[FILENAME_MAX];
int no;
for(no = start ; no <= end ; ++no){
snprintf(filename, sizeof(filename), "file05-data-%d.txt", no);
if(NULL==(file=fopen(filename, "r"))){
fprintf(stderr, "%s can't open.\n", filename);
//return 3;
continue;
}
/* input && output
char line[128];
while(fgets(line, sizeof(line), file)){
printf("%s", line);
}
*/
fclose(file);
}
return 0;
}
./practice 10 13
This is fine, but your usage of argc and argv is incorrect. I am assuming here that you are trying to open file# 10, 11, 12, 13.
1st put a check whether you are running the binary with right no of inputs (I think you are asking for two arguments) by:
if(argc!=3)
{
// print error msg & exit
}
And to build the file names:
char newfile[MAX_SIZE];
for(i=atoi(argv[1]); i<atoi(argv[2]); i++)
{
snprintf(newfile, "file-data-%d", i);
//open this file, read data, and then loop to the next file
}
That's it!

(C) Program doesn't print all values from input file

Working with C.
OK so this is probably something obvious but for some reason my program will only print a certain number of values from a .dat input file as opposed to printing all of them. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N = 0;
int j;
float i;
const char Project_Data[] = "FloatValues.dat";
FILE *input = fopen(Project_Data, "r");
if(input != (FILE*) NULL)
{
while(fscanf(input, "%e", &i) == 1)
{
printf("%e\n",i);
++N;
}
printf("\t The number of values in this file is: %d\n", N);
fclose(input);
}
else
printf("Input file could not be read.\n");
return(0);
}
Yeah, so there's about 100000 values or so to be printed yet I only seem to be able to get 20000. The values in the file are ordered sequentially and the compiler only seems to start printing nearer the bottom of the file, after about 80000 or so values.
Anybody know where I'm going wrong?

Resources