I am new to C and i am trying to iteratively call line in stream and check to see if it contains my search string or if it is null. I cant figure out how to make this check, i get a warning saying [Warning] comparison between pointer and integer or [Warning] assignment makes pointer from integer without a cast whenever i try and do this. can anyone help? thanks.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
FILE *fpntr;
char *file_pathname, *first_line;
if (argc != 2) {
fprintf(stderr, "usage: %s FILE\n", argv[0]);
return EXIT_FAILURE;
}
file_pathname = argv[1];
if ((fpntr = fopen(file_pathname, "r")) == NULL ) {
fprintf(stderr, "Error opening file %s: %s\n", file_pathname, strerror(errno));
return EXIT_FAILURE;
} else {
grep_stream();
fclose(fpntr);
}
return EXIT_SUCCESS;
}
int grep_stream(FILE *fpntr, char *string, char *file_pathname) {
//warning is on next line
while ((? = get_next_line(fpntr)) == NULL ) {
perror("Error reading line");
exit(EXIT_FAILURE);
}
elseif()
{
printf("First line in : %s \n %s", file_pathname, string);
}
}
char *get_next_line(FILE *fpntr) {
char *buff = malloc(101);
int pos = 0;
int next;
while ((next = fgetc(fpntr)) != '\n' && next != EOF) {
buff[pos++] = next;
}
buff[pos] = '\0';
if (buff != NULL ) {
return buff;
} else
return NULL ;
}
Remember that C code is compiled top-to-bottom. The function get_next_line isn't declared by the time the while line is read.
Either move get_next_line's definition to before main's, or forward-declare it by saying:
char *get_next_line(FILE *fpntr);
beforehand. The reason that you're getting a warning instead of an error is that undeclared functions are assumed to return int and no assumptions are made about their parameters. That is, they have the type int().
Also, properly format your code for both your sake and of those who will be answering your questions (or working with you.)
add a * to the pointer of integer to convert it from pointer to integer
... i am trying to iteratively call line in stream...
Why not use fgets()?
Secondly, to match a substring in a string, you can use strstr()
Please use standard C library instead of re-inventing the wheel. It saves the day usually.
#include <assert.h> // I'm too dumb to program without assertions!
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
//#include <unistd.h> I prefer stdlib.h, couldn't see any need for non-portable header...
#define MAX_LINE (101) // define funky constants in one place for easy changing later.
// declare functions before using them
void grep_stream(FILE *fpntr, char *file_pathname);
char *get_next_line(FILE *fpntr);
int main(int argc, char *argv[]) {
FILE *fpntr;
char *file_pathname;
if (argc != 2) {
fprintf(stderr, "usage: %s FILE\n", argv[0]);
return EXIT_FAILURE;
}
file_pathname = argv[1];
if ((fpntr = fopen(file_pathname, "r")) == NULL ) {
fprintf(stderr, "Error opening file %s: %s\n", file_pathname, strerror(errno));
return EXIT_FAILURE;
}
else {
grep_stream(fpntr, file_pathname);
fclose(fpntr);
}
return EXIT_SUCCESS;
}
void grep_stream(FILE *fpntr, char *file_pathname) {
char* line;
int got_first = 0;
assert(fpntr);
assert(file_pathname); // I worry the guy who wrote main() might be an idiot like me!
//warning is on next line [not anymore!]
while ((line = get_next_line(fpntr)) != NULL ) {
if(!got_first) {
printf("First line in : %s \n%s\n", file_pathname, line);
got_first = 1;
}
// if we're not going to use it, let's not leak memory
free(line);
}
}
char *get_next_line(FILE *fpntr) {
char *buff = malloc(MAX_LINE);
int pos = 0;
int next;
assert(buff != NULL); // wouldn't it be nice to know malloc() worked?
while ((next = fgetc(fpntr)) != '\n' && next != EOF) {
buff[pos++] = (char)next;
assert(pos < (MAX_LINE-1)); // don't want to be right back on SO with a seg fault, eh?
}
buff[pos] = '\0';
if(next == EOF) {
free(buff);
buff = NULL;
}
return buff;
}
Related
In my program, I can currently read char by char a file with given name "fichier1.txt", but what I'm looking for is to store a line(line char pointer here) and then display it that way :
-ligne 1 : content line 1
-line 2 : content line 2
-ect...
I've tried to store char by char but since it's a pointer and I'm yet that much familiar with pointers I'm not able to store a line and then reuse the pointer to store the char of the next line.
I have to say that it's part of a school projet and I have to use POSIX standard.
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int read_fd, write_fd;
off_t offset = 0;
char lu;
struct stat statFd;
char *fichier = "fichier1.txt";
read_fd = open(fichier,O_RDONLY);
stat(fichier, &statFd);
if(read_fd == -1){
perror("open");
exit(EXIT_FAILURE);
}
int i = 0;
char * line; // variable to store line
while(lseek(read_fd,offset, SEEK_SET) < statFd.st_size)
{
if(read(read_fd, &lu, 1) != -1)
{
printf("%c",lu);
offset++;
} else {
perror("READ\n");
close(read_fd);
close(write_fd);
exit(EXIT_FAILURE);
}
}
return 0;
}
I'd like to use open() function and not fopen()
Since you are able to read character after character from the file, the logic in while loop will be used to store an entire line (up to 199 characters, you can increase it though) at once in an array & then display it:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
FILE *fptr=fopen( "fichier1.txt","r");
int i;
char arr[200]; //THIS ARRAY WILL HOLD THE CONTENTS OF A LINE TEMPORARILY UNTIL IT IS PRINTED
int temp_index=0,line_number=1;;
memset(arr,'\0',sizeof(arr));
while((i=getc(fptr))!=EOF)
{
if(i!='\n')
{
arr[temp_index++]=i;
}
if(i=='\n')
{
printf(line %d: %s\n",line_number++,arr);
temp_index=0;
memset(arr,'\0',sizeof(arr));
}
}
return 0;
}
Calling lseek at every iteration may be inefficient and may fail on devices which are incapable of seeking. I would write a program along these lines below if I don't need to store lines.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int lc = 0; /* line count */
int c; /* character read */
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while ((c = fgetc(fp)) != EOF) {
printf("line %d: ", ++lc);
while (c != '\n' && c != EOF) {
putchar(c);
c = fgetc(fp);
}
putchar('\n');
}
return 0;
}
Or, a program using fgets to read a line at once:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main (void)
{
int lc = 0; /* line count */
char buf[4096]; /* buffer to store the line read */
bool newline = true;
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while (fgets(buf, sizeof buf, fp) != NULL) {
if (newline)
printf("line %d: ", ++lc);
printf("%s", buf);
newline = strchr(buf, '\n');
}
return 0;
}
I'm just getting started into file I/O and am trying to build a function that will simply copy a file to destination.
This program compiles however an empty file is created and nothing is copied. Any advice?
#include <stdio.h>
int copy_file(char FileSource[], char FileDestination[]) {
char content;
FILE *inputf = fopen(FileSource, "r");
FILE *outputf = fopen(FileDestination, "w");
if (inputf == NULL)
;
printf("Error: File could not be read \n");
return;
while ((content = getc(inputf)) != EOF) putc(content, inputf);
fclose(outputf);
fclose(inputf);
printf("Your file was successfully copied");
return 0;
}
int main() {
char inputname[100];
char outputname[100];
printf("Please enter input file name: \n");
scanf("%s", &inputname);
printf("Please write output file name: \n");
scanf("%s", &outputname);
copy_file(inputname, outputname);
return 0;
}
There are few bugs in the code you mentioned. These two below statement
scanf("%s", &inputname);
scanf("%s", &outputname);
Are wrong as inputname and outputname are char array and array name itself address so you no need to give &inputname to scanf(). For e.g
scanf("%s",inputname);
scanf("%s",outputname);
Also ; at the end of if statement is not serving correct purpose as you expected.
This
if(inputf == NULL);
Should be
if(inputf == NULL){
/*error handling */
}
As pointed by other, getc() returns int not char. From the manual page of getc()
int getc(FILE *stream);
And this
putc(content, inputf);
Change to
putc(content, outputf); /* write the data into outputf */
Your line :
putc(content, inputf);
needs to change to
putc(content, outputf);
This code has a lot of problems:
if(inputf == NULL);
printf("Error: File could not be read \n");
return;
It is the equivalent of
if(inputf == NULL)
{
;
}
printf("Error: File could not be read \n");
return;
You have a stray ; that terminates you if statement, and whitespace doesn't matter much at all with C.
So your if statement does nothing, and your code will always emit the "Error: File could not be read" message and return without doing anything else.
What you probably want:
if(inputf == NULL)
{
printf("Error: File could not be read \n");
return;
}
This is a perfect example of why a lot of C programmers always use braces after if statements. ALWAYS.
There are multiple problems in your code:
content must be declared as int: getc() returns an int with the value of the byte read from the file or the special negative value EOF at end of file. Storing that to a char variable loses information, making the test for EOF either ambiguous (if char is signed) or always false (if char is unsigned by default).
you should pass outputf to putc.
you should return from the copy_file function if fopen fails to open either file.
you should pass the maximum number of characters to read for the filenames
you should check the return value of scanf() to avoid undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int copy_file(const char *FileSource, const char *FileDestination) {
int content;
FILE *inputf, *outputf;
if ((inputf = fopen(FileSource, "r")) == NULL) {
printf("Error: cannot open input file %s\n", FileSource);
return -1;
}
if ((outputf = fopen(FileDestination, "w")) == NULL) {
printf("Error: cannot open output file %s\n", FileDestination);
fclose(inputf);
return -1;
}
while ((content = getc(inputf)) != EOF)
putc(content, inputf);
fclose(outputf);
fclose(inputf);
printf("Your file was successfully copied");
return 0;
}
int main() {
char inputname[100];
char outputname[100];
printf("Please enter input file name: \n");
if (scanf("%99s", inputname) != 1)
return 1;
printf("Please write output file name: \n");
if (scanf("%99s", &outputname) != 1)
return 1;
copy_file(inputname, outputname);
return 0;
}
Use sendfile() is more simple and efficient for copying file. You can view more detail about sendfile() by man sendfile.
#include <stdio.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{
printf("Usage: %s <srcfile> <dst_file>\n", argv[0]);
return 1;
}
char *src_file = argv[1];
char *dst_file = argv[2];
int src;
int dst;
ssize_t size;
struct stat stat_buf;
if ((src = open(src_file, O_RDONLY)) < 0)
{
printf("Can not open %s\n", src_file);
return -1;
}
if (fstat(src, &stat_buf) < 0)
{
printf("Can stat %s\n", src_file);
close(src);
return -2;
}
if ((dst = open(dst_file, O_CREAT|O_WRONLY, stat_buf.st_mode)) < 0)
{
printf("Can not open %s\n", dst_file);
return -1;
}
if ((size = sendfile(dst, src, NULL, stat_buf.st_size)) < 0)
{
printf("Fail to copy file, size: %ld\n", size);
}
else
{
printf("Success, size: %ld\n", size);
}
close(src);
close(dst);
return 0;
}
I'm really stuck on this problem. I'm trying to write a program in C that will take a file, and check to see if every line is in alphabetical order.
So the text file
apple
banana
grape
grape
orange
The program would print to stdout "Lines are in order". If the lines are out of order it would print say the lines are out of order and print the first pair of lines where that occurs.
The main thing I'm having trouble with is just debugging, I keep getting a segmentation fault and I'm not sure why. I don't think that theres an instance where I'm trying to dereference a null pointer and I don't think there's an instance where I try to assign something with more memory than a pointer can handle so I'm not sure what the issue is.
Below is my code, I'm really new to C so if there is anything obvious or fundamental flaws in my code I'd really appreciate being told so.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(char* argv[],int argc){
char* fileN = argv[1];
FILE* file = fopen(fileN,"r");
if (file == NULL){
perror("Error: Couldn't open file");
exit(1);
}else{
char *line = malloc(101*sizeof(char));
fgets(line,101,file);
char *comp = malloc(101*sizeof(char));
while(line){
fgets(comp,101,file);
if (comp){
if(strcmp(line,comp) > 0){
printf("Lines out of order\n");
printf("%s\n",line);
printf("%s\n",comp);
free(line);
free(comp);
fclose(file);
exit(1);
}
}
line = comp;
}
printf("Lines are ordered\n");
free(line);
free(comp);
fclose(file);
exit(0);
}
}
Thanks for the help everyone, here is a version of the program that works.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc,char* argv[]){
char* fileN = argv[1];
FILE* file = fopen(fileN,"r");
if (file == NULL){
perror("Error: Couldn't open file");
exit(1);
}else{
char line[101], comp[101];
fgets(line,101,file);
int bool = 1;
while(line && bool){
if (fgets(comp,101,file) != NULL){
if(strcmp(line,comp) > 0){
printf("Lines out of order\n");
printf("%s",line);
printf("%s\n",comp);
fclose(file);
exit(1);
}
strncpy(line,comp,100);
}else{
bool = 0;
}
}
printf("Lines are ordered\n");
fclose(file);
exit(0);
}
}
My mistakes were A) forgetting how to properly copy one string over to one another and B) not realizing that fgets would return null if it fails, that's what I needed to use to make sure my loops actually ends.
Tell me, if you need comments.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 100
int main(int argc, char* argv[]) {
char a[MAX_LINE];
char b[MAX_LINE];
FILE* fd = fopen(argv[1], "r");
if(!fd) {
puts("Error: Couldn't open file");
exit(1);
}
fgets(a, MAX_LINE, fd);
while(fgets(b, MAX_LINE, fd)) {
if(strcmp(a, b) > 0) {
puts("Lines out of order");
printf("a = %s", a);
printf("b = %s", b);
fclose(fd);
exit(1);
}
strcpy(a, b);
}
puts("Lines are ordered");
fclose(fd);
return 0;
}
I wrote C program of searching string. The problem is MyStrstr() function doesn't work with
command prompt. It only works with IDE. So, can anyone advise me how to fix the code for working with command prompt. With regards...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARGUMENT_COUNT 3
#define FILE_INDEX 2
#define SEARCH_INDEX 1
#define BUFFER 256
#define SUCCESS 0
#define ERRCODE_PARAM 1
#define ERRCODE_FILENAME 2
#define MSG_USAGE "String Search Program === EXER5 === by Newbie\nUsage: %s Search_String fileName"
#define MSG_ERROR "Can not open file. [%s]"
char* MyStrstr(char* pszSearchString, char* pszSearchWord);
int main(int argc, char* argv[])
{
FILE* pFile = NULL;
char szData[BUFFER];
char* pszCutString = NULL;
if(argc != ARGUMENT_COUNT) {
printf(MSG_USAGE, argv[0]);
return ERRCODE_PARAM;
}
pFile = fopen(argv[FILE_INDEX], "r");
if(pFile == NULL) {
printf(MSG_ERROR, argv[FILE_INDEX]);
return ERRCODE_FILENAME;
}
pszCutString = MyStrstr(szData, argv[SEARCH_INDEX]);
if(pszCutString != NULL) {
printf("%s", pszCutString);
}
fclose(pFile);
pFile = NULL;
return SUCCESS;
}
char* MyStrstr(char* pszSearchString, char* pszSearchWord) {
int nFcount = 0;
int nScount = 0;
int nSearchLen = 0;
int nIndex = 0;
char* pszDelString = NULL;
char cSLen = 0;
size_t len = 0;
if(pszSearchString == NULL || pszSearchWord == NULL) {
return NULL;
}
while(pszSearchWord[nSearchLen] != '\0') {
nSearchLen++;
}
if(nSearchLen <= 0){
return pszSearchString;
}
cSLen = *pszSearchWord++;
if (!cSLen) {
return (char*) pszSearchString;
}
len = strlen(pszSearchWord);
do {
char cMLength;
do {
cMLength = *pszSearchString++;
if (!cMLength)
return (char *) 0;
} while (cMLength != cSLen);
} while (strncmp(pszSearchString, pszSearchWord, len) != 0);
return (char *) (pszSearchString - 1);
}
You want to open a file, search the contents of that file for a string and return/print that. You are instead doing:
char szData[256]; // <-- making an uninitialized buffer
char* pszCutString = NULL;
pFile = fopen(argv[2], "r"); // <-- Opening a file
pszCutString = MyStrstr(szData, argv[1]); // <-- searching the buffer
if(pszCutString != NULL) {
printf("%s", pszCutString);
}
fclose(pFile); // <-- Closing the file
So you never fill your buffer szData with the contents of the file noted in argv[2]. You're trying to search an uninitialized buffer for a string. You're luck the result is just "no output comes out".
You need to take the contents of the file in argv[2] and place it in the buffer szData then do the search. This could be accomplished by adding a call to a function like read() or fscanf()
Note 1:
I assume when you say this "worked" in the IDE, the code was a little different and you weren't using the command line arguments.
Note 2:
you should also check to fopen() worked before trying to read from/close pFile, and if your file is possibly larger than 256 characters you will need to change your code to either have a dynamically sized string, or you'll need to loop the buffer fills (but then you have to worry about breaking a word apart), or some other mechanism to check the full file.
I am getting a segmentation fault when I call my getField(char *line, int field) function in my while loop and I'm not sure why. I'm trying to pass a line to the function and a column number so that I can grab specific columns from each line in a csv file and print them to the screen. Thanks for input.
void getField(char *line, int field);
int main(int argc, char *argv[]) {
if(argc < 3) {
fprintf(stderr, "Too few arguments \"%s\".\n", argv[0]);
}
if(atoi(argv[1]) < 1) {
fprintf(stderr, "First argument must be >= 1 \"%s\".\n", argv[1]);
}
FILE *fp = fopen(argv[2], "r");
if(fp == NULL)
fprintf(stderr, "Cannot open file %s\n", argv[0]);
char buf[80];
while(fgets(buf, 80, fp) != NULL) {
getField(buf, atoi(argv[1]); // seg fault is happening here
}
return 0;
}
void getField(char *line, int field) {
printf("here2");
//char *ln = line;
int column = field - 1;
int idx = 0;
while(column) {
//printf("here");
if(line[idx] == ',') field--;
idx++;
}
for(int j = idx; ; ++j) {
if(line[j] == ',') break;
printf("%s", line[j]);
}
printf("\n");
printf("%d", idx);
}
One obvious error is that you have an infinite loop here, and you will eventually access illegal memory.
while(column) {
//printf("here");
if(line[idx] == ',') field--;
idx++;
}
You are not modifying column at all, so your loop cannot possibly end.
column will not update itself when you update field, so you will have to update it if you want it to update.
while(column) {
//printf("here");
if(line[idx] == ',') field--;
idx++;
column = field - 1;
}
Note on debugging segfaults using printf.
The function printf prints to stdout and stdout likes to buffer output. This means that sometimes if you try to find a segfault by moving a print statement down your code until it fails to print, you will misunderstand where the segfault it happening. In particular, a printf line that appears before the line that actually contains the segfault may not print even if you might expect it to.
If you want to use this strategy (instead of gdb), you can force it to print by using fflush(stdout); immediately after your debugging printf.
while(column) {
//printf("here");
if(line[idx] == ',') column--; // Changed field-- to column--
idx++;
}
In following line:
printf("%s", line[j]);
you are using the %s format specifier but you are passing a char as argument.
You probably want this (%c format specifier fot printing a char):
printf("%c", line[j]);
You are accessing out of bounds of the array in the function getField because the while loop never exits. This invokes undefined behaviour and most likely program crash due to segfault which is what is happening in your case. I suggest the following changes to your program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void getField(char *line, int field);
int main(int argc, char *argv[]) {
if(argc < 3) {
fprintf(stderr, "Too few arguments \"%s\".\n", argv[0]);
return 1; // end the program
}
if(atoi(argv[1]) < 1) {
fprintf(stderr, "First argument must be >= 1 \"%s\".\n", argv[1]);
return 1; // end the program
}
FILE *fp = fopen(argv[2], "r");
if(fp == NULL) {
fprintf(stderr, "Cannot open file %s\n", argv[0]);
return 1; // end the program
}
char buf[80];
while(fgets(buf, 80, fp) != NULL) {
getField(buf, atoi(argv[1])); // seg fault is happening here
}
return 0;
}
void getField(char *line, int field) {
int len = strlen(line);
char temp[len + 1];
strcpy(temp, line);
int count = 0;
char ch = ',';
char *p = temp;
char *q = NULL;
while(count < field - 1) {
q = strchr(p, ch);
if(q == NULL) {
printf("error in the value of field\n");
return;
}
count++;
p = q + 1;
}
q = strchr(p, ch);
if(q != NULL)
*q = '\0';
else
temp[len-1] = '\0';
printf("%s\n", p);
}