I need to open a file, providing the full path. I used the function fopen to open the file, this works
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
file = fopen("C:\\Users\\Edo\\Desktop\\sample.docx","rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
but what i really need is to let the user choose which file he wants, however this code does not work .
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
I tried as input:
C:\Users\Edo\Desktop\sample.docx
C:\\Users\\Edo\\Desktop\\sample.docx
C:/Users/Edo/Desktop/sample.docx
C://Users//Edo//Desktop//sample.docx
none of them works
fgets leaves the newline on the end of your string. You'll need to strip that off:
path[strlen (path) - 1] = '\0';
You'll need to #include <string.h> for this too.
Thanks #lurker, he told me what was the problem, I fixed the code this way
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
strtok(path, "\n");
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
Related
im getting the fopen() is a directory and I am unable to locate my error,
it works perfectly with put and fgets. (Code That Works)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) // Use a valid prototype for main
{
char path[256] = "/your/fixed/path/";
size_t len = strlen(path);
puts("Enter a file name:");
// Get the file name leaving room for the path
if (fgets(path + len, sizeof(path) - len, stdin))
{
// Strip the trailing new line
path[strcspn(path, "\n")] = 0;
}
// Nothing to concat
FILE *file = fopen(path, "w");
// Always check the result of fopen
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
// Do your stuff ...
fclose(file);
return 0;
}
I want to use printf and scanf instead of puts and fgets, and when I use the below code I get the reply as fopen() is a directory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) // Use a valid prototype for main
{
char path[256] = "./casestudy/";
size_t len = strlen(path);
char *bt ="dd.txt";
// Get the file name leaving room for the path
if(path + len, sizeof(path) - len, bt)
{
// Strip the trailing new line
path[strcspn(path, "\n")] = 0;
}
// Nothing to concat
FILE *file = fopen(path, "w");
// Always check the result of fopen
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
// Do your stuff ...
fclose(file);
return 0;
}
You probably want something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) // using valid prototype for main
{
char path[256] = "./casestudy/";
puts("Enter the filename: ");
// Ask for filename from the user
char filename[256];
fgets(filename, sizeof(filename), stdin);
filename[strcspn(filename, "\n")] = 0; // remove trailing \n if any
// concatenate user provided filename to the path
strcat(path, filename);
// now path contains the full path to the file
printf("Full path is \"%s\".", path);
// FILE *f = fopen(path, ....)
// ...
}
Disclaimer: there is no checking for valid input, if the user provides a filename which is too long you'll get a buffer overflow. I let you deal with this as an exercise.
I don't know how to solve this problem. I have this function that prints all the .txt files that I have, but I also need to search and print, after each file name, some specific strings (of each file) that contain some word.
This is the part that prints the name of the files.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
int main() {
DIR* p;
struct dirent* pp;
p = opendir("./");
if (p != NULL) {
while ((pp = readdir(p)) != NULL) {
int length = strlen(pp->d_name);
if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
puts(pp->d_name);
}
(void)closedir(p);
}
return 0;
}
I need to search some specific words (three different words) and print the line in where are contained, that would be three different lines.
Right now the program prints this:
0_email.txt
1_email.txt
Inside this files that are like emails, I need to print he date of when they were send (Date:), who (To:) and the subject (Subject:). This information is not always in the same line.
I have try this code, that search the word, but I am not able to make the program search in all the files (because this files can increase and have different names, no I can't not do it name by name) and to search several times
FILE *fp;
char filename[]="0_email.txt",line[200],search_string[]="To:";
fp=fopen(filename,"r");
if(!fp){
perror("could not find the file");
exit(0);
}
while ( fgets ( line, 200, fp ) != NULL ){
if(strstr(line,search_string))
fputs ( line, stdout );
}
fclose ( fp );
This second code is one that I found in Internet, I have just learn c programming and I'm not very familiar with it.
Thanks for your help!
You need to learn about functions.
You roughly need following:
It's untested code and there is still a lot of improvments that should be done. It does not exactly what you want and I'm not even sure if it compiles, but it should give you an idea what you need to do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
int CheckFile(const char *filename)
{
FILE *fp;
char line[200], search_string[] = "To:";
fp = fopen(filename, "r");
if (!fp) {
perror("could not find the file");
exit(0);
}
while (fgets(line, 200, fp) != NULL) {
if (strstr(line, search_string))
fputs(line, stdout);
}
fclose(fp);
}
int main() {
DIR* p;
struct dirent* pp;
p = opendir("./");
if (p != NULL) {
while ((pp = readdir(p)) != NULL) {
int length = strlen(pp->d_name);
if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0)
CheckFile(pp->d_name);
}
(void)closedir(p);
}
return 0;
}
Write the program myuniq.c that contains a function void process_file(FILE* f) that reads all input from the given file one line at the time while keeping two consecutive lines in memory, and prints each line to the standard output if it is not equal to the previously read line.
^^This is the assignment i'm working on. My code below is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process_file(FILE* f);
int main()
{
FILE *fil = fopen("text.txt","r");
process_file(fil);
return 0;
}
void process_file(FILE* f)
{
FILE *fi = f;
char *firstLine = fgets(firstLine, 999, f);
char *secondLine = fgets(secondLine, 999, f);
while (feof(fi))
{
if (firstLine == secondLine)
{
puts(secondLine);
}
else
{
puts(firstLine);
puts(secondLine);
}
firstLine++;
secondLine++;
}
}
It compiled fine...but on every run it says core dumped. I can't see where I went wrong? Any ideas?
You don't check the return value of fopen, you don't allocate any memory for the strings into which you read, you don't continue reading input from the file, you don't correctly check for the end of input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MY_MAX_LINE 999
void process_file(FILE* f)
{
char firstLine[MY_MAX_LINE + 1];
char secondLine[MY_MAX_LINE + 1];
while (1)
{
if (!fgets(firstLine, sizeof(firstLine), f))
break;
puts(firstLine);
if (!fgets(secondLine, sizeof(secondLine), f))
break;
if (strncmp(firstLine, secondLine, sizeof(firstLine)))
puts(secondLine);
}
if (!feof(f))
perror("Problem reading from file"), exit(1);
}
int main(int argc, char **argv)
{
FILE *f = fopen("text.txt", "r");
if (!f)
perror("text.txt"), exit(1);
process_file(f);
fclose(f);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen( "Journey.txt" , "rt");
if(file){
while (fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else{
printf("Error");
}
return 1;
}
I want to read text file and use this code for adding BST.But If I run , Output is infinite loop.How can I read text file ?
Text file which I want to read:
80,15.04.2014,10,Henry Ford,NewYork,Paris,45
40,15.04.2014,11,Nikola Tesla,Londra,NewYork,40
Rather than read a text file using fscanf(), strongly recommend using fgets() and then parsing via sscanf(), strtok(), strtol(), etc. Check all function return values. It is much easier to cope with the unexpected - which is certainly what is happening in OP's case.
Using modified format from #BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main() {
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen("Journey.txt", "rt");
if (file) {
char buf[MAX*4 + 20*3 + 6*1 + 3];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int cnt = sscanf(buf, "%d,%499[^,],%d,%499[^,],%499[^,],%499[^,],%d",
&JourneyId, Date, &Hour, BusDriver, Departure, Destination,
&BusCapacity);
if (cnt != 7) {
printf("Unexpected input \"%s\"", buf);
break;
}
printf("%d,", JourneyId);
printf("%s\n", BusDriver);
}
fclose(file); // Be sure to close
} else {
printf("Error opening\n");
}
return 1;
}
As #BLUPIXY indicated, The following functions (tried on SuSE Linux / gcc)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE *file;
file = fopen( "Journey.txt" , "rt");
if(file)
{
// while(fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
while(fscanf(file,"%d,%11[^,],%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else
{
printf("Error");
}
return 1;
}
I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}
fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}