Writing selected text from a file to txt file using C - c

prefacing by saying, I've lurked in Stackoverflow and this is my first Question, but thank you all you kind souls for your contributions!
I am trying to write comments and classes from a .java file to a .txt file using C programming. I used the fgetc and fputc functions to do this and managed to write the whole file across, but when I try to communicate that I only want the comments right up to the class (so before the "{" and everything after the "}") it seems to not print anything. I am quite new to C and just a bit stuck. I have included my code below, any help would be super appreciated. Sorry if this is hard to understand, I am not natively English speaking.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *input = fopen("text.java", "r"); //opens file
FILE *comments = fopen("comments.txt", "w");
char ch;
ch = fgetc(input);
while(ch != EOF)
{
while(!strcmp(ch, "{"))
{
fputc(ch, comments);
ch = fgetc(input);
}
ch = fgetc(input);
}
fclose(input);
fclose(comments);
return 0;
}

As already pointed out in the comments section by someone else, your code has the following errors:
The return type of fgetc is int, not char. The value EOF cannot be represented in char, so you should not truncate the int return value to char. Instead, you should declare ch as an int.
The function strcmp is for comparing strings, not characters.
When calling fgetc in your inner loop, you are not checking the return value for EOF.
Also, your algorithm for solving the problem does not seem correct.
One way to solve the problem is for your program to always remember whether it is inside a brace or not, and to act accordingly. For example, you can declare a bool inside_brace variable which always specifies whether you are inside a brace or not, like this:
#include <stdio.h>
#include <stdlib.h>
//the following line is necessary for the "bool" data type
#include <stdbool.h>
int main( int argc, char **argv )
{
FILE *input = fopen("text.java", "r");
FILE *comments = fopen("comments.txt", "w");
int ch;
bool inside_brace = false;
while ( ( ch = fgetc(input) ) != EOF )
{
if ( !inside_brace )
{
if ( ch == '{' )
{
inside_brace = true;
continue;
}
fputc( ch, comments );
}
else //inside a brace
{
if ( ch == '}' )
{
inside_brace = false;
continue;
}
}
}
fclose(input);
fclose(comments);
return EXIT_SUCCESS;
}
Note that this solution will only work if you only have one nesting level of braces, i.e. that you don't have one { inside another { without first closing the first { with a }. If it is possible that you have more than one level of nesting, then the variable bool inside_brace will not be sufficient. Instead, you will need a counter to keep track of the current nesting level, for example like this:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
FILE *input = fopen("text.java", "r");
FILE *comments = fopen("comments.txt", "w");
int ch;
int nesting_level = 0;
while ( ( ch = fgetc(input) ) != EOF )
{
switch ( ch )
{
case '{':
nesting_level++;
continue;
case '}':
nesting_level--;
if ( nesting_level < 0 )
{
fprintf( stderr, "Error: Negative nesting level encountered!\n" );
return EXIT_FAILURE;
}
continue;
}
if ( nesting_level == 0 )
fputc( ch, comments );
}
}
fclose(input);
fclose(comments);
return EXIT_SUCCESS;
}

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)

How to display characters read from a file using getc()

When I try to read input from a file named "file1", my program correctly displays
the number of characters in the file, but in an unrecognized character format.
Below is the code
#include <stdio.h>
#include <stdlib.h>
void db_sp(FILE*);
int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
if(argc!=2) {
fprintf(stderr,"Program execution form: %s infile\n",argv[0]);
exit(1);
}
ifp=fopen(argv[1],"r");
if (ifp==NULL) printf("sdaf");
//ofp=fopen(argv[2],"w+") ;
db_sp(ifp);
fclose(ifp);
//fclose(ofp);
return 0;
}
void db_sp(FILE *ifp)
{
char c;
while(c=getc(ifp) !=EOF) {
//printf("%c",c);
putc(c,stdout);
if(c=='\n' || c=='\t' || c==' ')
printf("%c",c);
}
}
The problem is here:
while(c=getc(ifp) !=EOF){
Because of operator precendence, this getc(ifp) !=EOF gets executed first. Then c = <result of comparison> gets executed. Which is not the order you want.
Use parentheses to force the correct order.
while((c=getc(ifp)) !=EOF) {
Other notes:
getc returns an int so you should change the type of c to int.
Also, if you fail to open the file, you still continue execution. You should gracefully exit on failure.

Segmentation Fault on my while loop

I am trying to count the number of lines and characters whatever they may be in a file that I specify from argv. But I get a segmentation fault when I hit the while loop for some reason. The program runs fine without the while loop, though it only goes through once.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(argc != 2) {
return 0;
}
FILE *fp;
char c;
int lines = 0;
int chs = 0;
fp = fopen(argv[1], "r");
//Segmentation Fault happens here on the while loop
while((c = fgetc(fp)) != EOF) {
if(c == '\n') {
lines += 1;
}
else {
chs += 1;
}
}
printf("Charaters: %d\n", chs);
printf("lines: %d\n", lines);
if(fp){
fclose(fp);
}
return 0;
}
Your code needs to be follow Idiomatic C more closely.
You should validate fopen immediately, instead of after you've already attempted to use fp.
fgetc returns int, not char. This is because it needs to return side-channel information about the status of the stream (i.e. EOF), this information cannot be represented by char, but you can safely cast the int value to char if the value is not EOF.
Your code treats \r as a regular character when it is commonplace for \r\n to represent a line-break (not just a solitary \n), you might want to consider how you handle different character classes.
Your program does not handle non-trivial encodings (i.e. it will only correctly handle files in your system's native encoding, presumably ASCII). You should use a Unicode library to correctly read individual characters from a file: for example your program will treat a surrogate-pair in UTF-8 as two characters instead of 1, and would incorrectly count UTF-16 files.
Better:
FILE* fp = fopen( argv[1], "r" );
if( !fp ) {
printf( "Could not open file \"%s\" for reading.\r\n", argv[1] );
return 1;
}
int lines = 0;
int chars = 0;
int nc;
while( ( nc = fgetc( fp ) ) != EOF ) {
char c = (char)nc;
if ( c == '\n' ) lines++;
else if( c != '\r' ) chars++;
}
printf( "Characters: %d\r\nLines: %d\r\n", chars, lines );
fclose( fp );
return 0;

File wont open using fopen

I cannot seem to open this .txt file,it also doesnt work with .csv files
How do i get it to open?
(this is a program im trying to make that searches for a phrase inside a csv file)
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_WIDTH 320
int main(int argc, char *argv[]) {
int i = 0, j = 0;
char bigString[200];
FILE* csv;
csv = fopen("C:\Users\Ofek\Desktop\Folder\source.txt","r+t");
while (feof(csv) != 1)
{
if (fgetc(csv) != '\n')
{
char bigString[i] = fgetc(csv);
i++;
}
}
}
Replace all single backslashes with two backslashes:
C:\\Users\\Ofek\\Desktop\\Folder\\source.txt
Otherwise the character after the backslash will be interpreted as control characters.
there are several problems with the posted code. Here are a few:
1) do not use 'feof()' for a loop control, it will not work as expected.
2) when setting the bigString[i] variable, a second call to fgetc() is used. That results in the first, 3, 5, 7, etc characters being lost.
Suggest: save the results of the call to fgetc() in the 'if' statement and use that saved value.
the following code corrects 'most' of the problems in the posted code.
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int i = 0;
int inputChar;
char bigString[200] = {'\0'};
FILE* csv;
if( NULL == (csv = fopen("C:\\Users\\Ofek\\Desktop\\Folder\\source.txt","r+t") ) )
{ // then fopen failed
perror( "fopen for source.txt failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
while (EOF != ( inputChar = fgetc(csv) ) )
{
if ('\n' != inputChar)
{
bigString[i] = inputChar;
i++;
}
}
printf( "Input file, without newlines: %s\n", bigString );
return(0);
} // end function: main

hexadecimal to decimal conversion

The first piece of code prints each line in b.txt in a new line when it outputs it, and the second code is the conversion from hexadecimal to decimal. I am bad at writing big programs, so I split the task and write smaller programs instead. I am having trouble combining these two programs. Can anyone help ?
#include <stdio.h>
int main ( int argc, char **argv )
{
FILE *fp = fopen ( "b", "r");
char line[1024];
int ch = getc ( fp );
int index = 0;
while ( ch != EOF ) {
if ( ch != '\n'){
line[index++] = ch;
}else {
line[index] = '\0';
index = 0;
printf ( "%d\n", line );
}
ch = getc ( fp );
}
fclose ( fp );
return 0;
}
This is the second program
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int d;
FILE *fp;
FILE *ptr_file;
fp = fopen("normal_data","r"); // read mode
ptr_file =fopen("normal_decimal", "w");
while(fscanf(fp,"%x", &d) == 1)
{
fprintf(ptr_file, "%d /n", d);
}
while( ( d = fgetc(fp) ) != EOF )
fclose(fp);
return 0;
}
It is good programming practice to split your program in small related fragments.
But instead of using a main function everywhere , try making functions which accomplish certain tasks and add them to a header file.
This will make it much easier to write, debug and re-use the code.
In the above case, converting hexadecimal to decimal is clearly something which maybe used again and again.
So, just make a function int hex_to_dec(char* input); which takes a string of input e.g,"3b8c" and converts it to a decimal and returns the converted value.
You may also want to make function void printFile(FILE* fp); which takes the pointer to a file and prints it data to stdout.
You can add these and other functions you have made, to a header file like myFunctions.h and then include the file into whatever program you need to use your functions in.

Resources