C decryption program - c

When I compile the program and run it, it does not print anything. I believe the problem is on the while but I can't understand what is wrong. It is supposed to convert hex to ASCII and then the encrypted message.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(int argc, char **argv) {
int p;
//Opening a file
FILE*tp;
tp = fopen(argv[1], "r");
if(tp == NULL)
{
printf("Error opening file!\n");
return 0;
}
else
{
//Decryption code
while((p=fscanf(" %x",&p))!=EOF)
{
p=p >> 2;
p=p - 200;
printf(" %c",p);
}
}
return 1;
fclose(tp);
}

fscanf() returns number of input items successfully matched and assigned, not input items themselves. Also, as mentioned above, you need to pass file pointer to the function. Try this: while(fscanf(tp, "%x", &p) != EOF)

Looks like you need to specify and provide the FILE pointer "tp" to the fscanf function.

Related

How to Display Content of Multiple FIles Given in command Line argument in C

So I am trying to print the content of files which are given as an argument and the problem i am facing is when multiple arguments are passed it display the content of first file only.
Like if i give Input as a.txt b.txt c.txt it displays the output of a.txt and ends
the code i have written so far is:
#include<stdio.h>
int main(int argc,char*argv[])
{
if(argc<3)
{
printf("Insufficent Arguments");
exit(0);
}
int i;
FILE *fp;
char c;
for(i=1;i<argc;i++)
{
fp=fopen(argv[i],"r");
if (fp == NULL )
{
fprintf( stderr, "could not open file named %s!\n",argv[i] );
return 2;
}
else
{
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fp);
}
}
fclose( fp );
}
}
This code is after all possible modifications i have tried to resolve the problem
Please can anyone guide me what am i doing wrong?
After the first loop, you need to reset c. If you don't it keeps the last value from the previous file.
Also c needs to be int.
pseudo code
int main(int argc, char **argv) {
int c;
for (int i = 1; i < argc; i++) {
c = 0;
while (c != EOF) {
/* ... */
}
}
}
You may want to re-initialize your char 'c', that is used to check EOF.
After first iteration/file, it ends up with EOF and since this char is declared outside it retains its value across files. So for other file it will never go inside while loop.
option 1: Move your char c; declaration inside else
Or
option 2: re-initialize your c before while, c = fgetc(fp); (yes, you will have to restructure print)

My C Program Keep Crashing

i am trying to create an program to generate empty files. but when it try to run the program it crashes after taking inputs from the console .
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int create(char* filename)
{
char filext[10];
printf("\nEnter File Extension :");
fgets(filext);
FILE* fp;
fp = fopen(strcat(filename,strcat(".",filext)),"w");
if(!fp)
{
return 0;
}
fclose(fp);
return 1;
}
int main(int argc , char* argv[])
{
int f;
int i;
char buffer[33];
if (argc == 3)
{
for(i = 0; i < atoi(argv[2]) ; i++)
{
f = create(strcat(argv[1],itoa(i,buffer,10)));
if(f==0)
{
printf("error in creating files . check uac!!!");
}
else{
printf("\nfile Created ...\n");
}
}
}
else{
printf("syntax Error");
}
return 0;
}
when I try to run this program I get the following output
F:\selfcreatedtools\filegen>gcc gen.c
F:\selfcreatedtools\filegen>a level 100
Enter File Extension :php
after entering the extension the program crashes.
i am a beginner in c programming.
Your main problem lies in the strcat(".",filext) part of fp = fopen(strcat(filename,strcat(".",filext)),"w");
Try
strcat(filename, ".");
strcat(filename, filext);
fp = fopen(filename, "w");
And it might be better if the function definition header was made
int create(char filename[SIZE]) (where SIZE is a value less than the size filename will be) instead of int create(char* filename) since you are using strcat() to modify the string in the user-defined function create(). You wouldn't want illegal memory accesses that would cause errors if the string encroaches upon the memory allotted to something else.
A similar problem is there with using strcat() to modify the string at argv[1] as pointed out by Jonathan Leffler for which BLUEPIXY has provided a solution in the comments.

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)) {
...

Trying to simulate grep command

I am getting segmentation fault when i compile my code.
I am not getting what is wrong with my code will be happy if someone can help me.
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
FILE *fp;
char fline[100];
char *newline;
int i,count=0,occ=0;
fp=fopen(argv[1],"r");
while(fgets(fline,100,fp)!=NULL)
{
count++;
if(newline=strchr(fline,'\n'))
*newline='\0';
if(strstr(fline,argv[2])!=NULL)
{
printf("%s %d %s",argv[1],count,fline);
occ++;
}
}
printf("\n Occurence= %d",occ);
return 1;
}
See man open and man fopen:
FILE *fp;
...
fp=open(argv[1],"r");
open returns an integer, not a file pointer. Just change that line to
fp=fopen(argv[1],"r");
Note: OP edited this error out of the code in the question, for those who wonder what this is about
Which leads us to (some other minor issues addressed as well - see comments):
+EDIT: point to places where error checking should be done:
#include<stdio.h>
#include<string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *fp;
char fline[100];
char *newline;
int i, count = 0, occ = 0;
// for starters, ensure that enough arguments were passed:
if (argc < 3) {
printf("Not enough command line parameters given!\n");
return 3;
}
fp = fopen(argv[1], "r");
// fopen will return if something goes wrong. In that case errno will
// contain the error code describing the problem (could be used with
// strerror to produce a user friendly error message
if (fp == NULL) {
printf("File could not be opened, found or whatever, errno is %d\n",errno);
return 3;
}
while (fgets(fline, 100, fp) != NULL) {
count++;
if (newline = strchr(fline, '\n'))
*newline = '\0';
if (strstr(fline, argv[2]) != NULL) {
// you probably want each found line on a separate line,
// so I added \n
printf("%s %d %s\n", argv[1], count, fline);
occ++;
}
}
// it's good practice to end your last print in \n
// that way at least your command prompt stars in the left column
printf("\n Occurence= %d", occ);
return 1;
}
ps: so the error occurs during runtime and not during compile time - this distinction is quite crucial, because hunting down a compiler failure and solving a library usage error require rather different techniques...

fprintf not working C

I'm trying to make a simple program that writes to a .txt file, but this code won't work.
#include <stdio.h>
#include <string.h>
#include "main.h"
int main(int argc, const char * argv[])
{
FILE *f = fopen("text.txt", "w+");
char c[256];
printf("What's your name?\n");
scanf("%s", c);
fflush(f);
if (c!=NULL)
{
printf("not null\n");
int q = fprintf(f, "%s", c);
printf("%d", q);
}
else
{
printf("null\n");
}
printf("Hello, %s\n", c);
fclose(f);
return 0;
}
The printf returns that it's not null, and the int q returns whatever the length of the char is. Why isn't this writing to the file?
the printf returns that it's not null,
Thats because c is not null , since you have scanned your name string into it.
Why isn't this writing to the file?
The program is working fine , on my system.
-- Edit --
FILE *f = fopen("text.txt", "w+");
if (NULL == f)
perror("error opening file\n");
By doing the error handling this way , the exact reason (in your case permissions) , would be displayed,
Turns out I wasn't running with the correct permissions. Stupid mistake on my part.
First off, you've declared c in local scope, so it will never be NULL. If you want to check whether or not the user entered anything, check the length of c after you've scanned in the string:
if (strlen(c) == 0) {
///
}
Second, check whether or not you have permission to write to the current working directory. You should be checking the return value of fopen:
if (!f) {
fprintf(stderr, "Failed to open text.txt for writing\n");
}

Resources