read text file in xcode - c

i tried to read text file in xcode but this
"EXC_BAD_ACCESS message showed up when i tried to build my program
here is my code
and i put inputA.txt file in the same folder with project file
my friend told me that i should put txt file in debug folder is this why i cannot read txt
file in this code? please help me...
macbook user.
int main (int argc, const char * argv[]) {
FILE* fp;
char mychar;
char arr[50][2] = {0, };
int i = 0;
int j, k;
graphType* G_;
G_ = (graphType*)malloc(sizeof(graphType));
Create(G_);
fp = fopen("inputA.txt", "r");
//fp = fopen("inputB.txt", "r");
//fp = fopen("inputC.txt", "r");
while(1){
for(j = 0 ; j < 2 ; j++){
mychar = fgetc(fp);
if(mychar == EOF)
break;
else if(mychar == ' ')
continue;
arr[i][j] = mychar;
}
i++;
}

Per default your binary will be generated in ProjectDir/build/Mode, with Mode being Debug or Release, and will have that as its working directory. If you want to refer to a file in the project directory, you'd have to use ../../input.txt in that case.
The build locations are configured in the "Build Locations" section in a targets or projects build tab. The working directory can be manually changed in the settings for the executable ("General", "Set the working directory to:") if needed.
If you are having doubts then you can always find out what the working directory is:
#include <unistd.h>
int main() {
char buf[2048];
getcwd(buf, sizeof(buf));
printf("%s", buf);
}

Most likely inputA.txt is not in the same file as the binary. You should make sure the text file is copied to the output directory in your project (whether manually or by hand).
Also, fopen will return NULL if the file couldn't be opened, so you might want to add a check for that.
if (fp == NULL)
{
printf("Could not open file!");
return 1;
}

fopen is probably returning null because your text file isn't in the right place. Don't forget to check for null!

Related

fopen() doesn't work, despite the file clearly existing

When running my C code on WSL (ubuntu), I'm attempting to use fopen() on a file that 100%, positively, absolutely exists. And yet, it keeps saying that it doesn't exist despite it 100%, positively, absolutely existing.
int main (int argc, char *argv[]) {
char *path = "/bin/";
char *line;
// runs batch mode (tests use this mode)
if (argc == 2) {
char *line;
FILE *fp;
for (int i = 0; i < strlen(argv[1]); i++) {
if (argv[1][i] == '\n') {
argv[1][i] == '\0';
}
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("fopen");
}
I'm 100% certain that it's searching in the correct directory, because if I change the mode from "r" to "w", it creates a file with an identical name in the correct directory, right next to the file that already exists with the same name.
I'm seriously at the end of my rope. Absolutely none of this makes sense, especially how it doesn't pick up on there being duplicate files. Can someone please help?
Make certain your input file, that "exist" is not also used someplace else exclusively, like an editor.
Form a sibling file.
Example:
FILE *outf = fopen("test.txt", "w");
if (outf) {
fprintf(stderr, "<%s>\n", argv[1]);
fprintf(outf, "<%s>\n", argv[1]);
fclose(outf);
}
fp = fopen(argv[1], "r");
Was that test file located where you expected and with the expected contents?
Post that files contents.

stream != nullptr visual studio, simply printing values from txt file (C)

I am starting to program in Visual Studio (C) and I'm simply trying to print the values in the file, one by one. I can easily do this in my Eclipse version. (Which is the exact same code). My txt file is in project folder as seen here:
https://i.imgur.com/SPjZOrN.png
The code is as follows:
#include <stdio.h>
int main(int argc, char **argv) {
int c;
FILE *file;
const char* file_name = "ECG.txt";
file = fopen(file_name, "r");
int i = 0;
fscanf(file, "%d", &i);
while (!feof(file))
{
printf("%d ", i);
fscanf(file, "%d", &i);
}
fclose(file);
return 0;
}
When I run this, I get the error stream != nullptr how can I fix this?
It is very likely that your program tries to load the file from the directory where your executable resides, and not from that where your source files are (as you intend).
Either place the ECG.txt-file in the target directory or use absolute paths, e.g. "c:/myuser/myproject/ECG.txt";
Always check the result of fopen. If the result is NULL, then the file could not be opened (probably the reason for your runtime error). So the relevant portion of your program could loo as follows:
file = fopen(file_name, "r");
if (file) {
int i = 0;
while (fscanf(file, "%d", &i)==1) {
printf("%d ", i);
}
fclose(file);
} else {
printf("error opening file");
}

Can't write into a text file with for loop in c

I have an issue with writing strings into a txt file. My lines get overwritten every time. I use
gcc -Wall -o filename filename.c to compile and ./filename 10 Berlin cat resultat.txt to execute.
The txt file always has just one line (the last one) how can I save all the records.
I have a CSV file with city names and a number of residents, I need to filter for the City name and a minimum of residents.
What I tried so far:
.....
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "w");
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i<len; i++) {
fprintf(fp, "%s\n", result[i]);
}
fclose(fp);
}
int main(int argc,char **argv) {
int anzahl = atoi(argv[1]);
char *string_array[100];
char *erste_zeile;
erste_zeile = (char *) malloc(1000 * sizeof(char));
char staedte[MAX_LAENGE_ARR][MAX_LAENGE_STR];
char laender[MAX_LAENGE_ARR][MAX_LAENGE_STR];
int bewohner[MAX_LAENGE_ARR];
int len = read_file("staedte.csv", staedte, laender, bewohner);
for (int i = 0; i < len; ++i){
if (strcmp(argv[2],laender[i])==0 && anzahl < bewohner[i]){
snprintf(erste_zeile, 100,"Die Stadt %s hat %d Einwohner\n",staedte[i],bewohner[i]);
string_array[0] = erste_zeile;
// counter++;
write_file(string_array,1);
}
}
free(erste_zeile);
return 0;
}
Using the write_file() function outside of the for loop gives me null values. If anybody has an idea how to optimize the code please leave a comment or answer.
Each time you use FILE *fp = fopen("resultat.txt", "w"); what this does is delete the existing file and create a blank file for writing. What you're looking for is FILE *fp = fopen("resultat.txt", "a"); //a not w!. This will open the existing file and append content. If a file does not exist, one will be created. See this reference.
"w" -
Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a" -
Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
Also heed #Serge's advice about not opening the file for each record. Just open it once in the main and use the file handle to write to it. To make your current code work, you can do this:
void write_file(char *result[], int len) {
FILE *fp = fopen("resultat.txt", "a");//open for append
if (fp == NULL){
perror("resultat.txt");
exit(1);
}
for (int i=0; i < len; i++) {
fprintf(fp, "%s\n", result[i]);
}
fclose(fp);
}

C - Can't Create/Write to Files in VS2017

Question Edited
i'm giving a bit of a background on my problem hoping that'll help you understand it better:
I've recently updated my IDE to VC++ 2017 . I've written a basic assembler (for mips ISA) as part of my studies.
All worked well till i've reached the final part of printing the memory image to text file - i've noticed that altough the file pointer was allocated with a value(not NULL) after using "fopen", nothing was written to it.
Here is the definition and the opening of the input/output files(out of context since lack of space);
//File Pointers
FILE *fp_mem = NULL, *fp_asm = NULL;
/** Entering Main Function **/
// open files
fp_asm = fopen(argv[2], "r");
fp_mem = fopen(argv[1], "w");
if (fp_asm == NULL || fp_mem == NULL)
{
perror("ERROR");
exit(errno);
}
/** Assembler functionality **/
//write to file loop
for (i = 0; i <= highest_mem_access && i < MEM_SIZE; i++)
{
int temp = fprintf(fp_mem, "%08X\n", mem[i]);
}
//free label memory
free_label_list();
fclose(fp_asm);
fclose(fp_mem);
I tried various options instead of fpritnf - didn't work.
Most importantly - No File is created in my project directory!
Any idea guys? i'm pretty hopeless... I'll share more of my code if needed.
EDIT
This is a simple try to write to files in VS2015:
#include <stdio.h>
int main()
{
//FILE *fp = fopen("C:/Users/Tom/Desktop/test.txt", "w");
FILE *fp = fopen("test", "w");
if (fp == 0)
{
perror("ERR");
return(11);
}
int count = fprintf(fp,"Hello there,General Kenobi");
fclose(fp);
}
fp isn't NULL , Count = 26 after fprintf , No file located anywhere.
I also tried to write to another location(in comment) - same issue.

fopen and fopen_s seem to be crashing on long file names

I am using visual studio 2013 to build a c application
The code looks like this -
int main( int argc, char *argv[] )
{
char *InFilename = NULL;
char *OutFilename = NULL;
int ff_count; // counts the number of successive 0xff's read from the file buffer
int fpga_end, nios_start, nios_end; // used to report the size of each region
int file_length, file_index, temp_length, new_file_length;
int root_length;
int result;
FILE *infile = NULL;
FILE *outfile = NULL;
printf("Start JIC 2 rbf\r\n");
if ((argc != 2))
{
printf("\r\n\r\nV1.2 - Usage: <jic2rbf> <name of jicfile> \r\n");
printf("\r\n This program strips out the header info at the top of the file\r\n");
printf("\r\n and most of the ff's at the bottom. \r\n");
exit(1);
}
//
// Extract the name of the input file up to the '.' and use it to create the output file name with a .rbf extension.
//
InFilename = argv[1];
root_length = strcspn(InFilename,".");
printf("Root len = %d\r\n",root_length);
OutFilename = (char *)malloc(root_length+EXT_LENGTH);
memcpy(OutFilename,InFilename,root_length);
OutFilename[root_length] = 0;
strcat(OutFilename,".rbf");
printf("In file to be used %s\r\n", InFilename);
printf("Out file to be used %s\r\n", OutFilename);
result = fopen_s(&outfile, OutFilename, "wb");
if (result)
{
printf("Cannot open this file %s\r\n - 0x%x", OutFilename, result);
return 0;
}
printf("Open In - %d\r\n",result);
If I call this executable from a dos command line with -
E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_singleHID/par/q_series_hdcp_tx_dual_singleHID/output_files/q_series_hdcp_tx_dual_singleHID_elf.jic
The entire application works
If I call the application with the following command line -
E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_fpga/par/q_series_hdcp_tx_dual_fpga/output_files/q_series_hdcp_tx_dual_fpga_elf.jic
I do not see the printf("Open In - %d\r\n",result); output. The application just seems to crash.
I thought it might be some sort of buffer overflow in the file name but the shorter file name works..... If I cd to the directory with the file and call with the command line q_series_hdcp_tx_dual_fpga_elf.jic that works.
If I dir the file - E:/projects/Q4300_Hdcp/q_series_hdcp_base/fpga/q_series_hdcp_tx_dual_fpga/par/q_series_hdcp_tx_dual_fpga/output_files/q_series_hdcp_tx_dual_fpga_elf.jic
I see the file.......
I do not know how to catch the exception or what else to pursue to resolve this, any ideas would be great.
Thanks,
Martin
Try changing this line:
OutFilename = (char *)malloc(root_length+EXT_LENGTH);
to this:
OutFilename = malloc(1 + root_length + EXT_LENGTH);
to allocate space for the null terminator. Also, no need to cast malloc's return value.
DOS has some severe limits on command line length
so when the command line is too long, problems such as you are experience will occur.
Did you really mean that your using Visual Studio and Windows?
Many of the limitations of DOS have been carried forward into Windows and Visual Studio

Resources