I can see the last printf output of y but the fpc turns null.
I suspected for double quotes in fopen function but not could not find a solution: how to fix it?
Part of the code ;
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST %s\n",y);
When I run the code;
Error opening file.
TEST /Users/lessons/AbstractLesson.java
Here is the full code;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LINESIZE 1024
int main(void){
char *arr_lines, *line;
char buf_line[LINESIZE];
int num_lines = 0;
char buf[10240];
// open file
FILE *fp = fopen("/tmp/file", "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_line, LINESIZE, fp))
if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n'))
num_lines++;
// allocate memory
arr_lines = (char*)malloc(num_lines * 1024 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
line=arr_lines;
while (fgets(line, LINESIZE, fp))
if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n'))
line += LINESIZE;
// print first four lines
char *y = &arr_lines[1024*2];
FILE *fpc = fopen(y, "r");
//FILE *fp1 = fopen(arr_lines, "r");
if (fpc == NULL) {
printf("Error opening file.\n");
//return -1;
}
printf("TEST [%s]\n",y);
//x = &arr_lines[1024*0];
// y = *x;
// finish
fclose(fp);
return 0;
}
Change printf("TEST %s\n", y) to printf("TEST \"%s\"\n", y) so we can see if you have any extra whitespace characters in the filename.
fgets() returns the new line, if it's there. I didn't see where your code clears the newline. Does your path string include the new line?
Beyond that, fopen() is almost certainly working correctly. The only options are 1) The path is not correct, 2) the path has whitespace or other invalid characters, or 3) the file is not available for reading.
If you don't have a new line in your path, then you simply haven't provided enough information to resolve this issue.
I suspect the path, /Users/lessons/AbstractLesson.java, is wrong. It looks like an OSX path and it might be missing the username between Users and lessons.
Related
I'm writing a program said in this post title. I take reference at this webpage.
https://www.includehelp.com/c-programs/c-program-to-print-given-number-of-lines-of-a-file-like-head-command-in-linux.aspx
Here are the codes from that webpage.
#include <stdio.h>
int main(int argc, char * argv[])
{
FILE *fp; // file pointer
char *line = NULL;
int len = 0;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (getline(&line, &len, fp) != -1)
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line); fflush(stdout);
}
// close file
fclose(fp);
return 0;
}
My problem is the getline function. Since I'm not using Linux that function's giving error in my compiler. I tried to change it to fgets function. This is my revised codes.
I got two errors in the line ' while (fgets(&line, bufferLength, fp) != -1)'.
Error: passing argument 1 of 'fgets' from incompatible pointer type.
Error: comparison between pointer and integer.
My question is - how can I modify the program using fgets? Many thanks to anyone who can work this out.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fp; // file pointer
char *line = NULL;
int bufferLength = 255;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (fgets(&line, bufferLength, fp) != -1)
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line);
fflush(stdout);
}
// close file
fclose(fp);
return 0;
}
Your program should compile and run correctly follows:
//c program to print given number of lines from beginning of a file
//file name and number of lines must be supply as command line argument
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
FILE* fp; // file pointer
char* line = malloc(255);
int bufferLength = 255;
int cnt = 0;
if( argc < 3)
{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name N\" format.\n");
return -1;
}
// open file
fp = fopen(argv[1],"r");
// checking for file is exist or not
if( fp == NULL )
{
printf("\n%s file can not be opened !!!\n",argv[1]);
return 1;
}
// read lines from file one by one
while (fgets(line,bufferLength, fp))
{
cnt++;
if ( cnt > atoi(argv[2]) )
break;
printf("%s",line);
fflush(stdout);
}
// close file
fclose(fp);
free(line);
return 0;
}
we have two main problems, first
char * line = NULL;
line is a line of characters, a string if you want to call it that, so we must reserve enough memory to accommodate a complete line, and we do this with the malloc function, as seen in the program, the other problem we have with fgets, this function returns a pointer therefore we cannot compare the value returned by fgets with an integer, the declaration
while (fgets (line, bufferLength, fp))
is equivalent to running the loop while fgets is other than NULL. Finally we must use line instead of &line, the latter asks for the address of the line pointer, and not the address it points to.
There's no need to keep track of more than a single character. Reading full lines is overkill. Just do:
#include <stdio.h>
#include <stdlib.h>
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = fopen(path, mode);
if( fp == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
int
main(int argc, char **argv)
{
int count = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
FILE *in = argc > 2 ? xfopen(argv[2], "r") : stdin;
int line = 0;
int c;
while( line < count && ( c = fgetc(in)) != EOF ) {
putchar(c);
if( c == '\n' ) {
line += 1;
}
}
}
Note that I've reversed the order of the arguments, so that stdin is read if only a count is given.
currently, I am writing code in c program for printing small portion of contents from the input file. Actually, in my code I can able to print just one single line. but, i have to print next 5 lines after that one line.
I am new to programming, please help to solve this problem**
code is given below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lineNumber = 2;
int main()
{
FILE *file;
char line[100];
int count = 0;
///Open LS-dyna file to read
file = fopen("P:\\tut_c\\read\\df-read\\in.txt", "r");
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
else if ( file != NULL )
{
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
if (count == lineNumber)
{
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
The first logical error occurs in your while loop, first iteration, when you close the file and return 0.
Next, there is no reason to have a counter for your lines, since there are many c functions that can handle finding the end of file (eof).
Instead:
Use a while loop for iteration through the file.
Use a standard library c function for file reading.
Check if file has reached the end.
If the line is still valid, then print the line.
Here is some code to reiterate:
int main()
{
FILE *file;
file = fopen("file.txt", "r");
if (!file){ // check if file exists
perror("fopen");
exit(EXIT_FAILURE);
}
else { // if file exists, then...
char line[256];
while(fgets(line, sizeof line, file)){
printf("\n str %s ", line);
}
fclose(file);
}
return 0;
}// end main
I'm trying to read the number of a txt file like this:
input=20
output=10
hidden=5
....
I tried with this code:
char line[30];
char values[100][20];
int i = 0;
FILE *fp;
fp = fopen("myFile.txt", "r");
if(fp == NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
sscanf(line, "%[^=]", values[i])
printf("%s\n", values[i]);
i++;
}
fclose(fp);
But I obtain only the first word and never the number after the =.
I get
input
output
etc
instead of
20
10
5
etc
How can I get the number??
This line
sscanf(line, "%[^=]", values[i]);
means "read everything up to, but not including, the = sign into values[i]".
If you are interested in the numeric part after the equal sign, change the call as follows:
sscanf(line, "%*[^=]=%19s", values[i]);
This format line means "read and ignore (because of the asterisk) everything up to, and including, the equal sign. Then read a string of length of up to 19 characters into values[i]".
Demo.
Don't use sscanf() for that, redeclare values to store the integers like
int values[LARGE_CONSTANT_NUMBER];
and after fgets() just use strchr
char *number;
number = strchr(line, '=');
if (number == NULL)
continue;
number += 1;
values[i] = strtol(number, NULL, 10);
you could also use malloc() and realloc() if you wish, to make the values array dynamic.
Try it if you like
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char line[100];
int values[100];
int i;
FILE *fp;
size_t maxIntegers;
fp = fopen("myFile.txt", "r");
if (fp == NULL)
{
perror("cannot open file\n");
return 0;
}
i = 0;
maxIntegers = sizeof(values) / sizeof(values[0]);
while ((fgets(line, sizeof(line), fp) != NULL) && (i < maxIntegers))
{
char *number;
number = strchr(line, '=');
if (number == NULL) /* this line does not contain a `=' */
continue;
values[i++] = strtol(number + 1, NULL, 10);
printf("%d\n", values[i - 1]);
}
fclose(fp);
return 0;
}
with this technique you avoid unecessarily storing the number as a string.
So the assignment is to implement a substring search program using an input file to be searched from and an input to be searched. I created the following code:
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
FILE *fp;
fp = fopen(argv[1],"r");
if (fp == NULL)
{
printf("Error");
return 0;
}
char* tmpp[100];
int count = 0;
char* nexts = argv[2];
char* tmp = fgets(tmpp,100,fp);
while(tmp = strstr(tmp,nexts))
{
count++;
tmp++;
}
printf("%d\n\n",count);
fclose(fp);
return 0;
}
The program compiles but when i go to implement it in the ubuntu terminal as:
echo "aabb" >beta
./a.out beta a
1
Why isnt the program using the first argument (argv[1]) as beta and the second argument (argv[2]) as a correctly?
You should open a file and then read bytes from that file into temporary buffer:
FILE *file = fopen("file", "r");
while (1) {
char buffer[BUFSIZ+1];
size_t nread = fread(buffer, 1, sizeof(buffer)-1, file);
if (nread == 0) break; // read error or EOF
buffer[nread] = 0;
// chunk with BUFSIZ amount of bytes is available via buffer (and is zero-terminated)
}
If you want to search for string/pattern in a file, be aware that looked pattern in file may cross your chunk-size boundary, for example: you look for "hello", and BUFSIZ is 512. File contains "hello" at byte 510. Obviously, if you read by 512, you will get the first chunk ending with "he", and the second chunk starting with "llo". Probability of this situation is nonzero for all chunk sizes (except SIZE_MAX, but that buffer size is impossible by other reasons). Dealing with borders may be very complicated.
Close...but this is closer:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s file pattern\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL)
{
fprintf(stderr, "Error: failed to open file %s for reading\n", argv[1]);
return 1;
}
char tmpp[1000];
int count = 0;
char* nexts = argv[2];
while (fgets(tmpp, sizeof(tmpp), fp) != 0)
{
char *tmp = tmpp;
while ((tmp = strstr(tmp, nexts)) != 0)
{
count++;
tmp++;
}
}
printf("%d\n", count);
fclose(fp);
return 0;
}
The main difference is that this loops reading multiple lines from the input file. Yours would only work on files with a single line of input.
I need, in ANSI C, to open a file, to read all of its lines into a dynamically allocated array of strings, and to print the first four lines. The file may be any size up to 2^31-1 bytes, while each line is at most 16 characters. I have the following, but it does not seem to work:
#define BUFSIZE 1024
char **arr_lines;
char buf_file[BUFSIZE], buf_line[16];
int num_lines = 0;
// open file
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_file, BUFSIZE, fp))
if (!(strlen(buf_file) == BUFSIZE-1 && buf_file[BUFSIZE-2] != '\n'))
num_lines++;
// allocate memory
(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
while (!feof(fp)) {
fscanf(fp, "%s", buf_line);
strcpy(arr_lines[num_lines], buf_line);
num_lines++;
}
// print first four lines
printf("%s\n%s\n%s\n%s\n", arr_lines[0], arr_lines[1], arr_lines[2], arr_lines[3]);
// finish
fclose(fp);
I am having trouble on how to define arr_lines in order to write into this and to easily access its elements.
There are a few issues in your code, but the main one is that in the malloc line you are de-referencing an uninitialized pointer. Also, unless your lines consist of a single word, you should use fgets() instead of fscanf(...%s...) because the latter returns after reading a word, not a line. Even if your lines are words, it's safer to use the same type of loop that you used to count lines anyway, otherwise you risk reading more lines than you allocated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
#define LINESIZE 16
char *arr_lines, *line;
char buf_line[LINESIZE];
int num_lines = 0;
// open file
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_line, LINESIZE, fp))
if (!(strlen(buf_line) == LINESIZE-1 && buf_line[LINESIZE-2] != '\n'))
num_lines++;
// allocate memory
arr_lines = (char*)malloc(num_lines * 16 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
line=arr_lines;
while (fgets(line, LINESIZE, fp))
if (!(strlen(line) == LINESIZE-1 && line[LINESIZE-2] != '\n'))
line += LINESIZE;
// print first four lines
printf("%s\n%s\n%s\n%s\n", &arr_lines[16*0], &arr_lines[16*1], &arr_lines[16*2], &arr_lines[16*3]);
// finish
fclose(fp);
return 0;
}
Hope this helps!
Change
(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char));
to
arr_lines = malloc(num_lines * sizeof(char*));
then in the while loop below it, add
arr_lines[n] = malloc(16 * sizeof(char));