File wont open using fopen - c

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

Related

Writing selected text from a file to txt file using 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;
}

How can I read a multi-line TXT file with varying formats in C?

I have an input text file which looks something like this:
1(1.230000e+00)
2(1.230000e+00)
(1.230000e+00 1.230000e+00)
3(1.230000e+00)
(1.230000e+00 1.230000e+00)
.
.
.
I want to be able to read each line separately and distinguish between them. For example, for the first line, I want to store 100 in one variable as an int and I want to store 1.230000e+00 in another variable as a double. This is what I have tried:
fscanf(fp, "%d(%le)\n", &varInt, &varDouble);
This works for the first line. But how can I loop through and do this for all the lines AND also read the 3rd line using:
fscanf(fp, "(%le %le)\n", &varDouble1, &varDouble2);
To give some context, after reading each line, I will do some processing and then read the next line. Depending on the format of the line, I will do different type of processing.
Any help is appreciated! Thank you!
fscanf(3) is almost unusable unless the input is strictly controlled. It's hard to distinguish between I/O errors and parsing errors. That's why it's much more common to read each line with fgets(3), and then scan it with sscanf(3).
Because sscanf returns the number of elements parsed, you can use that to determine if a scan works as expected. No need to peek at the input: if you got what you expected, you're done, else try scanning some other way. Here's a working example:
#include <assert.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int
main( int argc, char *argv[] ) {
if( argc < 2 ) {
errx(EXIT_FAILURE, "syntax: %s filename", argv[0]);
}
FILE *input = fopen(argv[1], "r");
if( !input ) {
err(EXIT_FAILURE, "could not open '%s'", argv[0]);
}
static char line[128];
int n;
while( fgets(line, sizeof(line), input) != NULL ) {
double d1, d2;
int quantum;
if( 2 == sscanf(line, "%d(%lf)", &quantum, &d1) ) {
printf( "ok: %d\t%7.2f\n", 100 * quantum, d1 );
} else if( 2 == sscanf(line, "(%lf %lf)", &d1, &d2) ) {
printf( "ok: %7.2f\t%7.2f\n", d1, d2 );
} else {
printf( ">>> %s\n", line );
}
}
if( !feof(input) ) {
err(EXIT_FAILURE, "error reading %s", argv[1]);
}
return EXIT_SUCCESS;
}
If you discover other patterns, it's easy to add them. Note that when fgets fails, the program returns success only if we reached end of file.
If you generate the file, add fixed size prefix for the length of line. E.g. 016:1(1.230000e+00)\n. Then read 4 bytes with fread, convert string to int with strtol and read rest of line (\n is included in length). Finally split the values with strtok( str, "( )" ).
As mentioned in the comments, you can read a full line and then determine the format of the line and parse the line accordingly. The following code does what you want. However, production worthy code would probably more robustly interpret the format of each line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *GetStringNoBeginWhitespace( char *str )
{
static const char whitespace[] = " \f\n\r\t\v";
return(str + strspn(str, whitespace));
}
int main(int argc, char *argv[])
{
char *line = NULL;
FILE *fp;
char buffer[255];
int i;
double d,d1;
fp = fopen("data.txt", "r");
while(fgets(buffer, 255, fp))
{
buffer[strlen(buffer)-1] = 0x00;
line = GetStringNoBeginWhitespace( buffer );
if( line )
{
fputs(line, stdout);
if( isdigit((int)line[0] ))
{
printf("\tFormat is x(.......)\n");
if( sscanf(line,"%d(%le)\n", &i, &d) == 2 )
{
printf(" %d %le\n", i, d);
}
else
{
printf("\tUnknown format....\n");
}
}
else if( line[0] == '(' )
{
printf("\tFormat is ( ...... ....... )\n");
if( sscanf(line, "(%le %le)\n", &d, &d1) == 2 )
{
printf(" %le %le\n", d, d1);
}
else
{
printf("\tUnknown format....\n");
}
}
else
{
printf("\tUnknown format....\n");
}
}
}
fclose(fp);
return(0);
}
Output:
jnorton#ubuntu:~/source$ ./a.out
1(1.230000e+00) Format is x(.......)
1 1.230000e+00
2(1.230000e+00) Format is x(.......)
2 1.230000e+00
(1.230000e+00 1.230000e+00) Format is ( ...... ....... )
1.230000e+00 1.230000e+00
3(1.230000e+00) Format is x(.......)
3 1.230000e+00
(1.230000e+00 1.230000e+00) Format is ( ...... ....... )
1.230000e+00 1.230000e+00
data.txt file:
1(1.230000e+00)
2(1.230000e+00)
(1.230000e+00 1.230000e+00)
3(1.230000e+00)
(1.230000e+00 1.230000e+00)

Reading and checking a file's content in C

So I am writing a program in C that takes in a few command-line arguments and also reads a file and prints it to standard out. This is my code thus far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char* argv[] ) {
char* file_path;
float a;
float b;
char filedata[200];
if (argc != 4) {
printf("Error: 4 arguments are required.\n");
return -1;
}
file_path = argv[1];
a = atof(argv[2]);
b = atof(argv[3]);
if( a == 0.0 ) {
printf("Error: bad float arg\n");
return -1;
}
if( b == 0.0 ) {
printf("Error: bad float arg\n");
return -1;
}
FILE* fp = fopen( file_path, "r");
if( fp == NULL ){
printf( "Error: bad file; %s\n", file_path);
return -1;
}
while( fgets( filedata, 200, fp ) ){
printf("%s", filedata);
}
fclose(fp);
}
At the very bottom I have began to read a file. What I am trying to do is find files that contain the characters "#A#" and "#B#" and then print an error message when files containing these characters are not present.
Unfortunately, a simple if statement will not work in this scenario as I am not checking for equality but rather whether or not something is present.
If anybody could tell me about any C functions that are able to read and check the contents of a file, along with a few more specifics, then I would highly appreciate it!
After taking each line (into 'filedata') simply use the strstr function to check if it contains that substring "#A#" etc.
if strstr finds the substring it will return a pointer to it, otherwise it will return a NULL pointer.
So you should write something like this:
if ( strstr(filedata, "#A#") == NULL )
printf("Error\n");
but since you are looking at the entire file for this substring, you need to check all the lines before you conclude that there is an error.

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.

Replace string with another

I am just not sure why my replaceWord isn't going in to the file at all i have used all the commented out and so on and so forth. I am just trying to replace with with the text received from the command line argument. I know i might be far off I was just looking for a relatively easy way to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( int argc, char *argv[] )
{
if ( argc != 4 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename\n", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
char* wordReplace = argv[1];
char* replaceWord = argv[2];
FILE *file = fopen( argv[3], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
char string[100];
int len = 0;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( (fscanf( file, "%s", string ) ) != EOF )
{
len = strlen(string);
printf( "%s\n", string );
if(strcmp(string, wordReplace) == 0){
//fseek (file, (-strlen(string) + 1), 1);
//fputc(*replaceWord,file);
//replaceWord++;
//strcpy(string, replaceWord);
fprintf(file,"%s",replaceWord);
fputs(replaceWord, file);
printf("\n%d\n", len);
}
}
fclose( file );
}
}
printf("\n");
return 0;
}
You've opened the file in r ie read mode and trying to write to it.
Also after correcting that, note that, the replaced word and word to be replaced have to be of the same size, if you want to replace the file in place. Else you will end up overwriting other data. And you need to use functions like fseek to reposition the internal file pointer as fp would have moved ahead after fscanf

Resources